From a47a3968d59076ddaa38755029bbd1ba1e053766 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Wed, 3 Jul 2024 17:12:17 +0200 Subject: [PATCH 01/30] feat: 1.6.x preview --- .github/workflows/publish.yml | 2 +- README.md | 2 +- .../account/create-anonymous-session.md | 2 +- .../account/create-email-password-session.md | 2 +- docs/examples/account/create-email-token.md | 2 +- docs/examples/account/create-j-w-t.md | 2 +- .../account/create-magic-u-r-l-token.md | 2 +- .../account/create-mfa-authenticator.md | 2 +- docs/examples/account/create-mfa-challenge.md | 2 +- .../account/create-mfa-recovery-codes.md | 2 +- .../examples/account/create-o-auth2session.md | 2 +- docs/examples/account/create-o-auth2token.md | 2 +- docs/examples/account/create-phone-token.md | 2 +- .../account/create-phone-verification.md | 2 +- docs/examples/account/create-push-target.md | 2 +- docs/examples/account/create-recovery.md | 2 +- docs/examples/account/create-session.md | 2 +- docs/examples/account/create-verification.md | 2 +- docs/examples/account/create.md | 2 +- docs/examples/account/delete-identity.md | 2 +- .../account/delete-mfa-authenticator.md | 2 +- docs/examples/account/delete-push-target.md | 2 +- docs/examples/account/delete-session.md | 2 +- docs/examples/account/delete-sessions.md | 2 +- .../account/get-mfa-recovery-codes.md | 2 +- docs/examples/account/get-prefs.md | 2 +- docs/examples/account/get-session.md | 2 +- docs/examples/account/get.md | 2 +- docs/examples/account/list-identities.md | 2 +- docs/examples/account/list-logs.md | 2 +- docs/examples/account/list-mfa-factors.md | 2 +- docs/examples/account/list-sessions.md | 2 +- docs/examples/account/update-email.md | 2 +- docs/examples/account/update-m-f-a.md | 2 +- .../account/update-magic-u-r-l-session.md | 2 +- .../account/update-mfa-authenticator.md | 2 +- docs/examples/account/update-mfa-challenge.md | 2 +- .../account/update-mfa-recovery-codes.md | 2 +- docs/examples/account/update-name.md | 2 +- docs/examples/account/update-password.md | 2 +- docs/examples/account/update-phone-session.md | 2 +- .../account/update-phone-verification.md | 2 +- docs/examples/account/update-phone.md | 2 +- docs/examples/account/update-prefs.md | 2 +- docs/examples/account/update-push-target.md | 2 +- docs/examples/account/update-recovery.md | 2 +- docs/examples/account/update-session.md | 2 +- docs/examples/account/update-status.md | 2 +- docs/examples/account/update-verification.md | 2 +- docs/examples/avatars/get-browser.md | 2 +- docs/examples/avatars/get-credit-card.md | 2 +- docs/examples/avatars/get-favicon.md | 2 +- docs/examples/avatars/get-flag.md | 2 +- docs/examples/avatars/get-image.md | 2 +- docs/examples/avatars/get-initials.md | 2 +- docs/examples/avatars/get-q-r.md | 2 +- docs/examples/databases/create-document.md | 2 +- docs/examples/databases/delete-document.md | 2 +- docs/examples/databases/get-document.md | 2 +- docs/examples/databases/list-documents.md | 2 +- docs/examples/databases/update-document.md | 2 +- docs/examples/functions/create-execution.md | 3 +- docs/examples/functions/get-execution.md | 2 +- docs/examples/functions/list-executions.md | 2 +- docs/examples/graphql/mutation.md | 2 +- docs/examples/graphql/query.md | 2 +- docs/examples/locale/get.md | 2 +- docs/examples/locale/list-codes.md | 2 +- docs/examples/locale/list-continents.md | 2 +- docs/examples/locale/list-countries-e-u.md | 2 +- docs/examples/locale/list-countries-phones.md | 2 +- docs/examples/locale/list-countries.md | 2 +- docs/examples/locale/list-currencies.md | 2 +- docs/examples/locale/list-languages.md | 2 +- docs/examples/messaging/create-subscriber.md | 2 +- docs/examples/messaging/delete-subscriber.md | 2 +- docs/examples/storage/create-file.md | 2 +- docs/examples/storage/delete-file.md | 2 +- docs/examples/storage/get-file-download.md | 2 +- docs/examples/storage/get-file-preview.md | 2 +- docs/examples/storage/get-file-view.md | 2 +- docs/examples/storage/get-file.md | 2 +- docs/examples/storage/list-files.md | 2 +- docs/examples/storage/update-file.md | 2 +- docs/examples/teams/create-membership.md | 2 +- docs/examples/teams/create.md | 2 +- docs/examples/teams/delete-membership.md | 2 +- docs/examples/teams/delete.md | 2 +- docs/examples/teams/get-membership.md | 2 +- docs/examples/teams/get-prefs.md | 2 +- docs/examples/teams/get.md | 2 +- docs/examples/teams/list-memberships.md | 2 +- docs/examples/teams/list.md | 2 +- .../teams/update-membership-status.md | 2 +- docs/examples/teams/update-membership.md | 2 +- docs/examples/teams/update-name.md | 2 +- docs/examples/teams/update-prefs.md | 2 +- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2355 ++++++++--------- lib/services/avatars.dart | 388 ++- lib/services/databases.dart | 259 +- lib/services/functions.dart | 156 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++-- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 40 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 203 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 182 files changed, 4579 insertions(+), 4932 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c188fab0..7053b5e1 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,4 +20,4 @@ jobs: run: flutter pub get - uses: dart-lang/setup-dart@v1 - name: Publish - run: dart pub publish --force \ No newline at end of file + run: dart pub publish --force diff --git a/README.md b/README.md index 3cf6fa7a..63a87a79 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite) [![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord) -**This SDK is compatible with Appwrite server version 1.5.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-flutter/releases).** +**This SDK is compatible with Appwrite server version 1.6.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-flutter/releases).** Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the Flutter SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs) diff --git a/docs/examples/account/create-anonymous-session.md b/docs/examples/account/create-anonymous-session.md index 8eea4bf4..173b07af 100644 --- a/docs/examples/account/create-anonymous-session.md +++ b/docs/examples/account/create-anonymous-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index d90d9e26..6b498790 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-email-token.md b/docs/examples/account/create-email-token.md index 2532d82d..497d91a4 100644 --- a/docs/examples/account/create-email-token.md +++ b/docs/examples/account/create-email-token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-j-w-t.md b/docs/examples/account/create-j-w-t.md index 1e33c888..5af6e3d3 100644 --- a/docs/examples/account/create-j-w-t.md +++ b/docs/examples/account/create-j-w-t.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-magic-u-r-l-token.md b/docs/examples/account/create-magic-u-r-l-token.md index 8c430c86..8ac49e82 100644 --- a/docs/examples/account/create-magic-u-r-l-token.md +++ b/docs/examples/account/create-magic-u-r-l-token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-mfa-authenticator.md b/docs/examples/account/create-mfa-authenticator.md index b43ec1a6..4ea79898 100644 --- a/docs/examples/account/create-mfa-authenticator.md +++ b/docs/examples/account/create-mfa-authenticator.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-mfa-challenge.md b/docs/examples/account/create-mfa-challenge.md index 64bcb367..bbd95ea7 100644 --- a/docs/examples/account/create-mfa-challenge.md +++ b/docs/examples/account/create-mfa-challenge.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-mfa-recovery-codes.md b/docs/examples/account/create-mfa-recovery-codes.md index 68fdaaa4..aa3b78b1 100644 --- a/docs/examples/account/create-mfa-recovery-codes.md +++ b/docs/examples/account/create-mfa-recovery-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-o-auth2session.md b/docs/examples/account/create-o-auth2session.md index ea651e73..2679f9eb 100644 --- a/docs/examples/account/create-o-auth2session.md +++ b/docs/examples/account/create-o-auth2session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-o-auth2token.md b/docs/examples/account/create-o-auth2token.md index 4227359c..4f62b811 100644 --- a/docs/examples/account/create-o-auth2token.md +++ b/docs/examples/account/create-o-auth2token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-phone-token.md b/docs/examples/account/create-phone-token.md index efcdcbe8..5a096ceb 100644 --- a/docs/examples/account/create-phone-token.md +++ b/docs/examples/account/create-phone-token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-phone-verification.md b/docs/examples/account/create-phone-verification.md index ad0da61d..f80bbaad 100644 --- a/docs/examples/account/create-phone-verification.md +++ b/docs/examples/account/create-phone-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-push-target.md b/docs/examples/account/create-push-target.md index be945eec..33a98cf7 100644 --- a/docs/examples/account/create-push-target.md +++ b/docs/examples/account/create-push-target.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-recovery.md b/docs/examples/account/create-recovery.md index 8b8a41a8..70c52faa 100644 --- a/docs/examples/account/create-recovery.md +++ b/docs/examples/account/create-recovery.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-session.md b/docs/examples/account/create-session.md index 29aca9c5..b8170cc1 100644 --- a/docs/examples/account/create-session.md +++ b/docs/examples/account/create-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-verification.md b/docs/examples/account/create-verification.md index c3a4f0f7..99ba3cbe 100644 --- a/docs/examples/account/create-verification.md +++ b/docs/examples/account/create-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create.md b/docs/examples/account/create.md index 032c523e..324d0d99 100644 --- a/docs/examples/account/create.md +++ b/docs/examples/account/create.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-identity.md b/docs/examples/account/delete-identity.md index ab68036a..ae5cd50d 100644 --- a/docs/examples/account/delete-identity.md +++ b/docs/examples/account/delete-identity.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-mfa-authenticator.md b/docs/examples/account/delete-mfa-authenticator.md index 3f62177e..bc1cde4e 100644 --- a/docs/examples/account/delete-mfa-authenticator.md +++ b/docs/examples/account/delete-mfa-authenticator.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-push-target.md b/docs/examples/account/delete-push-target.md index 2081bf67..d80c97ec 100644 --- a/docs/examples/account/delete-push-target.md +++ b/docs/examples/account/delete-push-target.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-session.md b/docs/examples/account/delete-session.md index 7f84f82a..5bf98115 100644 --- a/docs/examples/account/delete-session.md +++ b/docs/examples/account/delete-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index c17afd0d..c00d2856 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get-mfa-recovery-codes.md b/docs/examples/account/get-mfa-recovery-codes.md index 008f8ced..f4e99b6e 100644 --- a/docs/examples/account/get-mfa-recovery-codes.md +++ b/docs/examples/account/get-mfa-recovery-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get-prefs.md b/docs/examples/account/get-prefs.md index 6b378996..2790e097 100644 --- a/docs/examples/account/get-prefs.md +++ b/docs/examples/account/get-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get-session.md b/docs/examples/account/get-session.md index 6954e51e..0be63f72 100644 --- a/docs/examples/account/get-session.md +++ b/docs/examples/account/get-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get.md b/docs/examples/account/get.md index 2790b57a..0bd26c02 100644 --- a/docs/examples/account/get.md +++ b/docs/examples/account/get.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-identities.md b/docs/examples/account/list-identities.md index 763e2533..758b054b 100644 --- a/docs/examples/account/list-identities.md +++ b/docs/examples/account/list-identities.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-logs.md b/docs/examples/account/list-logs.md index d3b06dd9..7a4ac11a 100644 --- a/docs/examples/account/list-logs.md +++ b/docs/examples/account/list-logs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-mfa-factors.md b/docs/examples/account/list-mfa-factors.md index 08186e3e..d66e8862 100644 --- a/docs/examples/account/list-mfa-factors.md +++ b/docs/examples/account/list-mfa-factors.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 0bde760d..4c363ccf 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-email.md b/docs/examples/account/update-email.md index 0ce8eb5e..2b5b73ec 100644 --- a/docs/examples/account/update-email.md +++ b/docs/examples/account/update-email.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-m-f-a.md b/docs/examples/account/update-m-f-a.md index 1f5f709b..5f65b7e9 100644 --- a/docs/examples/account/update-m-f-a.md +++ b/docs/examples/account/update-m-f-a.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-magic-u-r-l-session.md b/docs/examples/account/update-magic-u-r-l-session.md index 2eb4b33d..0f584d75 100644 --- a/docs/examples/account/update-magic-u-r-l-session.md +++ b/docs/examples/account/update-magic-u-r-l-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-mfa-authenticator.md b/docs/examples/account/update-mfa-authenticator.md index 4f5074e2..9fb8f54c 100644 --- a/docs/examples/account/update-mfa-authenticator.md +++ b/docs/examples/account/update-mfa-authenticator.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-mfa-challenge.md b/docs/examples/account/update-mfa-challenge.md index 34c37801..6eac3466 100644 --- a/docs/examples/account/update-mfa-challenge.md +++ b/docs/examples/account/update-mfa-challenge.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-mfa-recovery-codes.md b/docs/examples/account/update-mfa-recovery-codes.md index 914366fb..29c0cff2 100644 --- a/docs/examples/account/update-mfa-recovery-codes.md +++ b/docs/examples/account/update-mfa-recovery-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-name.md b/docs/examples/account/update-name.md index dc2c4c6a..bf8048d0 100644 --- a/docs/examples/account/update-name.md +++ b/docs/examples/account/update-name.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-password.md b/docs/examples/account/update-password.md index 37c6ecf4..0e410601 100644 --- a/docs/examples/account/update-password.md +++ b/docs/examples/account/update-password.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-phone-session.md b/docs/examples/account/update-phone-session.md index f6871317..1ea87ddf 100644 --- a/docs/examples/account/update-phone-session.md +++ b/docs/examples/account/update-phone-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-phone-verification.md b/docs/examples/account/update-phone-verification.md index 0facc29f..d6681a63 100644 --- a/docs/examples/account/update-phone-verification.md +++ b/docs/examples/account/update-phone-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-phone.md b/docs/examples/account/update-phone.md index 24000c4b..0e530464 100644 --- a/docs/examples/account/update-phone.md +++ b/docs/examples/account/update-phone.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-prefs.md b/docs/examples/account/update-prefs.md index d83e25f9..15d3a8f5 100644 --- a/docs/examples/account/update-prefs.md +++ b/docs/examples/account/update-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-push-target.md b/docs/examples/account/update-push-target.md index 0311d0be..78d1b792 100644 --- a/docs/examples/account/update-push-target.md +++ b/docs/examples/account/update-push-target.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-recovery.md b/docs/examples/account/update-recovery.md index f87e8723..d12c24d3 100644 --- a/docs/examples/account/update-recovery.md +++ b/docs/examples/account/update-recovery.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-session.md b/docs/examples/account/update-session.md index 5a12ad27..bb600667 100644 --- a/docs/examples/account/update-session.md +++ b/docs/examples/account/update-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-status.md b/docs/examples/account/update-status.md index 8b7bc49c..da59e537 100644 --- a/docs/examples/account/update-status.md +++ b/docs/examples/account/update-status.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-verification.md b/docs/examples/account/update-verification.md index c3db86b8..98174f9f 100644 --- a/docs/examples/account/update-verification.md +++ b/docs/examples/account/update-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Account account = Account(client); diff --git a/docs/examples/avatars/get-browser.md b/docs/examples/avatars/get-browser.md index 6bc6e541..20b039a3 100644 --- a/docs/examples/avatars/get-browser.md +++ b/docs/examples/avatars/get-browser.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-credit-card.md b/docs/examples/avatars/get-credit-card.md index d5b96383..9f645f40 100644 --- a/docs/examples/avatars/get-credit-card.md +++ b/docs/examples/avatars/get-credit-card.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-favicon.md b/docs/examples/avatars/get-favicon.md index 10047b44..b4003ee0 100644 --- a/docs/examples/avatars/get-favicon.md +++ b/docs/examples/avatars/get-favicon.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-flag.md b/docs/examples/avatars/get-flag.md index 66a5b202..9751ae23 100644 --- a/docs/examples/avatars/get-flag.md +++ b/docs/examples/avatars/get-flag.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-image.md b/docs/examples/avatars/get-image.md index 15f3ea6e..4c140418 100644 --- a/docs/examples/avatars/get-image.md +++ b/docs/examples/avatars/get-image.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index 2d540a1d..c7df00f1 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-q-r.md b/docs/examples/avatars/get-q-r.md index 94b34bda..fa4c3f41 100644 --- a/docs/examples/avatars/get-q-r.md +++ b/docs/examples/avatars/get-q-r.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/databases/create-document.md b/docs/examples/databases/create-document.md index 6645b4ed..7970d033 100644 --- a/docs/examples/databases/create-document.md +++ b/docs/examples/databases/create-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/delete-document.md b/docs/examples/databases/delete-document.md index fc7c5ef1..138a5aeb 100644 --- a/docs/examples/databases/delete-document.md +++ b/docs/examples/databases/delete-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/get-document.md b/docs/examples/databases/get-document.md index 4f2ba3e3..7cdd4b04 100644 --- a/docs/examples/databases/get-document.md +++ b/docs/examples/databases/get-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/list-documents.md b/docs/examples/databases/list-documents.md index da43b17d..ec23cf0e 100644 --- a/docs/examples/databases/list-documents.md +++ b/docs/examples/databases/list-documents.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/update-document.md b/docs/examples/databases/update-document.md index 42f5b657..b4179209 100644 --- a/docs/examples/databases/update-document.md +++ b/docs/examples/databases/update-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index 6ca5e14b..d53f4bf9 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Functions functions = Functions(client); @@ -13,4 +13,5 @@ Execution result = await functions.createExecution( path: '', // optional method: ExecutionMethod.gET, // optional headers: {}, // optional + scheduledAt: '', // optional ); diff --git a/docs/examples/functions/get-execution.md b/docs/examples/functions/get-execution.md index 67439f40..84747806 100644 --- a/docs/examples/functions/get-execution.md +++ b/docs/examples/functions/get-execution.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/functions/list-executions.md b/docs/examples/functions/list-executions.md index 3902d6e7..a99078ce 100644 --- a/docs/examples/functions/list-executions.md +++ b/docs/examples/functions/list-executions.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index d94c5315..bde93e50 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Graphql graphql = Graphql(client); diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index 13c21eeb..35088d91 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Graphql graphql = Graphql(client); diff --git a/docs/examples/locale/get.md b/docs/examples/locale/get.md index b705b834..81ca1229 100644 --- a/docs/examples/locale/get.md +++ b/docs/examples/locale/get.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index c9ca3297..5b6d9755 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index b174e606..c4a4ef85 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-countries-e-u.md b/docs/examples/locale/list-countries-e-u.md index e3772f0f..eee42941 100644 --- a/docs/examples/locale/list-countries-e-u.md +++ b/docs/examples/locale/list-countries-e-u.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index 9e0ed748..5136d62a 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index 12c57042..c3eed1ec 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index 0d6662ee..e2300b4e 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index b2f22a16..83284e2f 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/messaging/create-subscriber.md b/docs/examples/messaging/create-subscriber.md index fc3b2596..85822f8e 100644 --- a/docs/examples/messaging/create-subscriber.md +++ b/docs/examples/messaging/create-subscriber.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Messaging messaging = Messaging(client); diff --git a/docs/examples/messaging/delete-subscriber.md b/docs/examples/messaging/delete-subscriber.md index 5cd62597..8551b2ef 100644 --- a/docs/examples/messaging/delete-subscriber.md +++ b/docs/examples/messaging/delete-subscriber.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Messaging messaging = Messaging(client); diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 55216ba3..77468915 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -3,7 +3,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/delete-file.md b/docs/examples/storage/delete-file.md index bab2a477..5e2525ea 100644 --- a/docs/examples/storage/delete-file.md +++ b/docs/examples/storage/delete-file.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file-download.md b/docs/examples/storage/get-file-download.md index 1a612be0..d8d18aa4 100644 --- a/docs/examples/storage/get-file-download.md +++ b/docs/examples/storage/get-file-download.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index 2649bb2c..09c8ddae 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file-view.md b/docs/examples/storage/get-file-view.md index 5d0e38e8..802bfa89 100644 --- a/docs/examples/storage/get-file-view.md +++ b/docs/examples/storage/get-file-view.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file.md b/docs/examples/storage/get-file.md index b7b894b4..6127932b 100644 --- a/docs/examples/storage/get-file.md +++ b/docs/examples/storage/get-file.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/list-files.md b/docs/examples/storage/list-files.md index f75ef6e3..a72d279f 100644 --- a/docs/examples/storage/list-files.md +++ b/docs/examples/storage/list-files.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/update-file.md b/docs/examples/storage/update-file.md index cca06533..320f24fb 100644 --- a/docs/examples/storage/update-file.md +++ b/docs/examples/storage/update-file.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index 1cf04267..b59c69c1 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/create.md b/docs/examples/teams/create.md index 04593d46..2cd7e4b2 100644 --- a/docs/examples/teams/create.md +++ b/docs/examples/teams/create.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/delete-membership.md b/docs/examples/teams/delete-membership.md index 38f47c79..6dfe00fd 100644 --- a/docs/examples/teams/delete-membership.md +++ b/docs/examples/teams/delete-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/delete.md b/docs/examples/teams/delete.md index 4107155b..3f6de53a 100644 --- a/docs/examples/teams/delete.md +++ b/docs/examples/teams/delete.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/get-membership.md b/docs/examples/teams/get-membership.md index 10fd9594..120c1294 100644 --- a/docs/examples/teams/get-membership.md +++ b/docs/examples/teams/get-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/get-prefs.md b/docs/examples/teams/get-prefs.md index b8f36922..a8d41f28 100644 --- a/docs/examples/teams/get-prefs.md +++ b/docs/examples/teams/get-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/get.md b/docs/examples/teams/get.md index 12ed636c..c29cefa4 100644 --- a/docs/examples/teams/get.md +++ b/docs/examples/teams/get.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/list-memberships.md b/docs/examples/teams/list-memberships.md index ca98b5f1..98557687 100644 --- a/docs/examples/teams/list-memberships.md +++ b/docs/examples/teams/list-memberships.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/list.md b/docs/examples/teams/list.md index 25aaafa4..3b70d345 100644 --- a/docs/examples/teams/list.md +++ b/docs/examples/teams/list.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-membership-status.md b/docs/examples/teams/update-membership-status.md index ae05c371..4e397747 100644 --- a/docs/examples/teams/update-membership-status.md +++ b/docs/examples/teams/update-membership-status.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index 41f2a9be..93514b96 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-name.md b/docs/examples/teams/update-name.md index 2b3b288d..13623107 100644 --- a/docs/examples/teams/update-name.md +++ b/docs/examples/teams/update-name.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-prefs.md b/docs/examples/teams/update-prefs.md index 8afb99ad..071bd951 100644 --- a/docs/examples/teams/update-prefs.md +++ b/docs/examples/teams/update-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject('<YOUR_PROJECT_ID>'); // Your project ID Teams teams = Teams(client); diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d32ccc8f..340c6b7f 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.5.x. +/// This SDK is compatible with Appwrite server version 1.5.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index 7a9feea2..6e1304df 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1197 +2,1164 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwt'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Add Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. add - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create 2FA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Add Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create 2FA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 1d419191..8eb0bb8b 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,201 +3,193 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 81f6723b..4ddd6dfe 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,87 +3,75 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 85ea7e48..5201aedc 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index ad7f2cfd..9e319b2d 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 5a0d6318..8e69f4d6 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '12.0.4', - 'X-Appwrite-Response-Format': '1.5.0', + 'X-Appwrite-Response-Format' : '1.5.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 0e027808..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -2,6 +2,7 @@ import 'package:http/http.dart' as http; import 'exception.dart'; import 'response.dart'; import 'dart:convert'; +import 'dart:developer'; import 'enums.dart'; class ClientMixin { @@ -39,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -67,6 +68,12 @@ class ClientMixin { Response prepareResponse(http.Response res, {ResponseType? responseType}) { responseType ??= ResponseType.json; + + String? warnings = res.headers['x-appwrite-warning']; + if (warnings != null) { + warnings.split(';').forEach((warning) => log('Warning: $warning')); + } + if (res.statusCode >= 400) { if ((res.headers['content-type'] ?? '').contains('application/json')) { final response = json.decode(res.body); @@ -99,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index bd6e2a8b..d56dc167 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,114 +2,97 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index c79b9ebe..fffb7c62 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index 389acea8..b47292ab 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -33,7 +33,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); if (_websok == null) { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From bf7aac5a909efb159e4b786b44f841b218499a38 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Wed, 3 Jul 2024 18:42:48 +0200 Subject: [PATCH 02/30] chore: bump version --- README.md | 2 +- lib/src/client_browser.dart | 2 +- lib/src/client_io.dart | 2 +- pubspec.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 63a87a79..d2b69715 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^12.0.4 + appwrite: ^13.0.0-rc.1 ``` You can install packages from the command line: diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 9e319b2d..6599822a 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -43,7 +43,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '12.0.4', + 'x-sdk-version': '13.0.0-rc.1', 'X-Appwrite-Response-Format': '1.5.0', }; diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 8e69f4d6..5a80eccb 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -64,7 +64,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '12.0.4', + 'x-sdk-version': '13.0.0-rc.1', 'X-Appwrite-Response-Format' : '1.5.0', }; diff --git a/pubspec.yaml b/pubspec.yaml index 9e62e8bc..887565dd 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 12.0.4 +version: 13.0.0-rc.1 description: Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter From 0c669d039300bff7bc48ef044f40b8418177442b Mon Sep 17 00:00:00 2001 From: root Date: Sat, 17 Aug 2024 08:48:22 +0000 Subject: [PATCH 03/30] chore: release rc --- README.md | 4 +- .../account/delete-mfa-authenticator.md | 1 - .../functions/get-deployment-download.md | 29 +++++ docs/examples/functions/get-template.md | 11 ++ docs/examples/functions/list-templates.md | 14 +++ lib/appwrite.dart | 2 +- lib/models.dart | 4 + lib/services/account.dart | 9 +- lib/services/avatars.dart | 2 + lib/services/functions.dart | 79 +++++++++++++- lib/src/client.dart | 2 +- lib/src/client_browser.dart | 14 +-- lib/src/client_io.dart | 4 +- lib/src/models/execution.dart | 5 + lib/src/models/template_function.dart | 103 ++++++++++++++++++ lib/src/models/template_function_list.dart | 28 +++++ lib/src/models/template_runtime.dart | 38 +++++++ lib/src/models/template_variable.dart | 48 ++++++++ lib/src/realtime.dart | 2 +- lib/src/realtime_browser.dart | 4 +- pubspec.yaml | 10 +- test/services/account_test.dart | 1 - test/services/functions_test.dart | 73 ++++++++++++- .../models/template_function_list_test.dart | 20 ++++ test/src/models/template_function_test.dart | 50 +++++++++ test/src/models/template_runtime_test.dart | 24 ++++ test/src/models/template_variable_test.dart | 28 +++++ 27 files changed, 576 insertions(+), 33 deletions(-) create mode 100644 docs/examples/functions/get-deployment-download.md create mode 100644 docs/examples/functions/get-template.md create mode 100644 docs/examples/functions/list-templates.md create mode 100644 lib/src/models/template_function.dart create mode 100644 lib/src/models/template_function_list.dart create mode 100644 lib/src/models/template_runtime.dart create mode 100644 lib/src/models/template_variable.dart create mode 100644 test/src/models/template_function_list_test.dart create mode 100644 test/src/models/template_function_test.dart create mode 100644 test/src/models/template_runtime_test.dart create mode 100644 test/src/models/template_variable_test.dart diff --git a/README.md b/README.md index d2b69715..e8b07298 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![pub package](https://img.shields.io/pub/v/appwrite?style=flat-square)](https://pub.dartlang.org/packages/appwrite) ![License](https://img.shields.io/github/license/appwrite/sdk-for-flutter.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-1.5.x-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-1.6.x-blue.svg?style=flat-square) [![Build Status](https://img.shields.io/travis/com/appwrite/sdk-generator?style=flat-square)](https://travis-ci.com/appwrite/sdk-generator) [![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite) [![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord) @@ -21,7 +21,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^13.0.0-rc.1 + appwrite: ^13.0.0-rc.2 ``` You can install packages from the command line: diff --git a/docs/examples/account/delete-mfa-authenticator.md b/docs/examples/account/delete-mfa-authenticator.md index bc1cde4e..66a0e897 100644 --- a/docs/examples/account/delete-mfa-authenticator.md +++ b/docs/examples/account/delete-mfa-authenticator.md @@ -8,5 +8,4 @@ Account account = Account(client); await account.deleteMfaAuthenticator( type: AuthenticatorType.totp, - otp: '', ); diff --git a/docs/examples/functions/get-deployment-download.md b/docs/examples/functions/get-deployment-download.md new file mode 100644 index 00000000..c6bda7d4 --- /dev/null +++ b/docs/examples/functions/get-deployment-download.md @@ -0,0 +1,29 @@ +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint + .setProject('<YOUR_PROJECT_ID>'); // Your project ID + +Functions functions = Functions(client); + +// Downloading file +UInt8List bytes = await functions.getDeploymentDownload( + functionId: '', + deploymentId: '', +) + +final file = File('path_to_file/filename.ext'); +file.writeAsBytesSync(bytes); + +// Displaying image preview +FutureBuilder( + future: functions.getDeploymentDownload( + functionId:'' , + deploymentId:'' , +), // Works for both public file and private file, for private files you need to be logged in + builder: (context, snapshot) { + return snapshot.hasData && snapshot.data != null + ? Image.memory(snapshot.data) + : CircularProgressIndicator(); + } +); diff --git a/docs/examples/functions/get-template.md b/docs/examples/functions/get-template.md new file mode 100644 index 00000000..f08ec612 --- /dev/null +++ b/docs/examples/functions/get-template.md @@ -0,0 +1,11 @@ +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint + .setProject('<YOUR_PROJECT_ID>'); // Your project ID + +Functions functions = Functions(client); + +TemplateFunction result = await functions.getTemplate( + templateId: '', +); diff --git a/docs/examples/functions/list-templates.md b/docs/examples/functions/list-templates.md new file mode 100644 index 00000000..bb14efc8 --- /dev/null +++ b/docs/examples/functions/list-templates.md @@ -0,0 +1,14 @@ +import 'package:appwrite/appwrite.dart'; + +Client client = Client() + .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint + .setProject('<YOUR_PROJECT_ID>'); // Your project ID + +Functions functions = Functions(client); + +TemplateFunctionList result = await functions.listTemplates( + runtimes: [], // optional + useCases: [], // optional + limit: 1, // optional + offset: 0, // optional +); diff --git a/lib/appwrite.dart b/lib/appwrite.dart index 340c6b7f..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.5.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/models.dart b/lib/models.dart index a6de0d82..df2bb3fc 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -9,6 +9,7 @@ part 'src/models/log_list.dart'; part 'src/models/file_list.dart'; part 'src/models/team_list.dart'; part 'src/models/membership_list.dart'; +part 'src/models/template_function_list.dart'; part 'src/models/execution_list.dart'; part 'src/models/country_list.dart'; part 'src/models/continent_list.dart'; @@ -36,6 +37,9 @@ part 'src/models/locale_code.dart'; part 'src/models/file.dart'; part 'src/models/team.dart'; part 'src/models/membership.dart'; +part 'src/models/template_function.dart'; +part 'src/models/template_runtime.dart'; +part 'src/models/template_variable.dart'; part 'src/models/execution.dart'; part 'src/models/country.dart'; part 'src/models/continent.dart'; diff --git a/lib/services/account.dart b/lib/services/account.dart index 6e1304df..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -184,7 +184,7 @@ class Account extends Service { } - /// Add Authenticator + /// Create Authenticator /// /// Add an authenticator app to be used as an MFA factor. Verify the /// authenticator using the [verify @@ -231,11 +231,10 @@ class Account extends Service { /// Delete Authenticator /// /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); final Map apiParams = { - 'otp': otp, }; final Map apiHeaders = { @@ -248,7 +247,7 @@ class Account extends Service { } - /// Create 2FA Challenge + /// Create MFA Challenge /// /// Begin the process of MFA verification after sign-in. Finish the flow with /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) @@ -1139,7 +1138,7 @@ class Account extends Service { } - /// Create phone verification (confirmation) + /// Update phone verification (confirmation) /// /// Use this endpoint to complete the user phone verification process. Use the /// **userId** and **secret** that were sent to your user's phone number to diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 8eb0bb8b..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -66,6 +66,7 @@ class Avatars extends Service { /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote /// website URL. /// + /// This endpoint does not follow HTTP redirects. Future getFavicon({required String url}) async { const String apiPath = '/avatars/favicon'; @@ -120,6 +121,7 @@ class Avatars extends Service { /// image at source quality. If dimensions are not specified, the default size /// of image returned is 400x400px. /// + /// This endpoint does not follow HTTP redirects. Future getImage({required String url, int? width, int? height}) async { const String apiPath = '/avatars/image'; diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 4ddd6dfe..ccaa6f63 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -6,6 +6,69 @@ class Functions extends Service { /// Initializes a [Functions] service Functions(super.client); + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + /// List executions /// /// Get a list of all the current user function execution logs. You can use the @@ -34,10 +97,12 @@ class Functions extends Service { /// current execution status. You can ping the `Get Execution` endpoint to get /// updates on the current execution status. Once this endpoint is called, your /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt, Function(UploadProgress)? onProgress}) async { final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); final Map apiParams = { + + 'body': body, 'async': xasync, 'path': path, @@ -47,10 +112,18 @@ class Functions extends Service { }; final Map apiHeaders = { - 'content-type': 'application/json', + 'content-type': 'multipart/form-data', }; - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + String idParamName = ''; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); return models.Execution.fromMap(res.data); diff --git a/lib/src/client.dart b/lib/src/client.dart index 5201aedc..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -1,6 +1,6 @@ import 'enums.dart'; import 'client_stub.dart' - if (dart.library.html) 'client_browser.dart' + if (dart.library.js_interop) 'client_browser.dart' if (dart.library.io) 'client_io.dart'; import 'response.dart'; import 'upload_progress.dart'; diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 6599822a..d5648d3b 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -3,7 +3,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_web_auth_2/flutter_web_auth_2.dart'; import 'package:http/http.dart' as http; import 'package:http/browser_client.dart'; -import 'package:universal_html/html.dart' as html; +import 'package:web/web.dart' as web; import 'client_mixin.dart'; import 'enums.dart'; import 'exception.dart'; @@ -43,8 +43,8 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.1', - 'X-Appwrite-Response-Format': '1.5.0', + 'x-sdk-version': '13.0.0-rc.2', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -113,9 +113,9 @@ class ClientBrowser extends ClientBase with ClientMixin { } Future init() async { - if (html.window.localStorage.keys.contains('cookieFallback')) { - addHeader('x-fallback-cookies', - html.window.localStorage['cookieFallback'] ?? ''); + final cookieFallback = web.window.localStorage['cookieFallback']; + if (cookieFallback != null) { + addHeader('x-fallback-cookies', cookieFallback); } _httpClient.withCredentials = true; } @@ -213,7 +213,7 @@ class ClientBrowser extends ClientBase with ClientMixin { debugPrint( 'Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.'); addHeader('X-Fallback-Cookies', cookieFallback); - html.window.localStorage['cookieFallback'] = cookieFallback; + web.window.localStorage['cookieFallback'] = cookieFallback; } return prepareResponse(res, responseType: responseType); } catch (e) { diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 5a80eccb..f724282b 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -64,8 +64,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.1', - 'X-Appwrite-Response-Format' : '1.5.0', + 'x-sdk-version': '13.0.0-rc.2', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index d56dc167..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -34,6 +34,8 @@ class Execution implements Model { final String errors; /// Function execution duration in seconds. final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; Execution({ required this.$id, @@ -52,6 +54,7 @@ class Execution implements Model { required this.logs, required this.errors, required this.duration, + this.scheduledAt, }); factory Execution.fromMap(Map map) { @@ -72,6 +75,7 @@ class Execution implements Model { logs: map['logs'].toString(), errors: map['errors'].toString(), duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), ); } @@ -93,6 +97,7 @@ class Execution implements Model { "logs": logs, "errors": errors, "duration": duration, + "scheduledAt": scheduledAt, }; } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart new file mode 100644 index 00000000..c3fcbe40 --- /dev/null +++ b/lib/src/models/template_function.dart @@ -0,0 +1,103 @@ +part of '../../models.dart'; + +/// Template Function +class TemplateFunction implements Model { + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } +} diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart new file mode 100644 index 00000000..dddb2c94 --- /dev/null +++ b/lib/src/models/template_function_list.dart @@ -0,0 +1,28 @@ +part of '../../models.dart'; + +/// Function Templates List +class TemplateFunctionList implements Model { + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; + + TemplateFunctionList({ + required this.total, + required this.templates, + }); + + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } +} diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart new file mode 100644 index 00000000..34209d13 --- /dev/null +++ b/lib/src/models/template_runtime.dart @@ -0,0 +1,38 @@ +part of '../../models.dart'; + +/// Template Runtime +class TemplateRuntime implements Model { + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } +} diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart new file mode 100644 index 00000000..df3982c7 --- /dev/null +++ b/lib/src/models/template_variable.dart @@ -0,0 +1,48 @@ +part of '../../models.dart'; + +/// Template Variable +class TemplateVariable implements Model { + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } +} diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index fffb7c62..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -1,5 +1,5 @@ import 'realtime_stub.dart' - if (dart.library.html) 'realtime_browser.dart' + if (dart.library.js_interop) 'realtime_browser.dart' if (dart.library.io) 'realtime_io.dart'; import 'realtime_subscription.dart'; import 'service.dart'; diff --git a/lib/src/realtime_browser.dart b/lib/src/realtime_browser.dart index 1567f64f..8e561033 100644 --- a/lib/src/realtime_browser.dart +++ b/lib/src/realtime_browser.dart @@ -1,6 +1,6 @@ import 'dart:convert'; import 'dart:async'; -import 'package:universal_html/html.dart' as html; +import 'package:web/web.dart' as web; import 'package:web_socket_channel/html.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import 'realtime_subscription.dart'; @@ -26,7 +26,7 @@ class RealtimeBrowser extends RealtimeBase with RealtimeMixin { } String? _getFallbackCookie() { - final fallbackCookie = html.window.localStorage['cookieFallback']; + final fallbackCookie = web.window.localStorage['cookieFallback']; if (fallbackCookie != null) { final cookie = Map.from(jsonDecode(fallbackCookie)); return cookie.values.first; diff --git a/pubspec.yaml b/pubspec.yaml index 887565dd..5cb048f7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 13.0.0-rc.1 +version: 13.0.0-rc.2 description: Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter @@ -20,16 +20,16 @@ dependencies: sdk: flutter cookie_jar: ^4.0.8 device_info_plus: ^10.1.0 - flutter_web_auth_2: ^3.1.1 + flutter_web_auth_2: ^3.1.2 http: '>=0.13.6 <2.0.0' package_info_plus: ^8.0.0 path_provider: ^2.1.3 - web_socket_channel: ^2.4.5 - universal_html: ^2.2.4 + web_socket_channel: ^3.0.0 + web: ^0.5.1 dev_dependencies: path_provider_platform_interface: ^2.1.2 - flutter_lints: ^3.0.2 + flutter_lints: ^4.0.0 flutter_test: sdk: flutter mockito: ^5.4.4 diff --git a/test/services/account_test.dart b/test/services/account_test.dart index d7bf0fb9..3f76e30c 100644 --- a/test/services/account_test.dart +++ b/test/services/account_test.dart @@ -308,7 +308,6 @@ void main() { final response = await account.deleteMfaAuthenticator( type: 'totp', - otp: '', ); }); diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 8707d054..96a8736d 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -54,6 +54,71 @@ void main() { functions = Functions(client); }); + test('test method listTemplates()', () async { + final Map data = { + 'total': 5, + 'templates': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.listTemplates( + ); + expect(response, isA()); + + }); + + test('test method getTemplate()', () async { + final Map data = { + 'icon': 'icon-lightning-bolt', + 'id': 'starter', + 'name': 'Starter function', + 'tagline': 'A simple function to get started.', + 'permissions': [], + 'events': [], + 'cron': '0 0 * * *', + 'timeout': 300, + 'useCases': [], + 'runtimes': [], + 'instructions': 'For documentation and instructions check out .', + 'vcsProvider': 'github', + 'providerRepositoryId': 'templates', + 'providerOwner': 'appwrite', + 'providerVersion': 'main', + 'variables': [], + 'scopes': [],}; + + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.getTemplate( + templateId: '', + ); + expect(response, isA()); + + }); + + test('test method getDeploymentDownload()', () async {final Uint8List data = Uint8List.fromList([]); + + when(client.call( + HttpMethod.get, + )).thenAnswer((_) async => Response(data: data)); + + + final response = await functions.getDeploymentDownload( + functionId: '', + deploymentId: '', + ); + expect(response, isA()); + + }); + test('test method listExecutions()', () async { final Map data = { 'total': 5, @@ -92,8 +157,12 @@ void main() { 'duration': 0.4,}; - when(client.call( - HttpMethod.post, + when(client.chunkedUpload( + path: argThat(isNotNull), + params: argThat(isNotNull), + paramName: argThat(isNotNull), + idParamName: argThat(isNotNull), + headers: argThat(isNotNull), )).thenAnswer((_) async => Response(data: data)); diff --git a/test/src/models/template_function_list_test.dart b/test/src/models/template_function_list_test.dart new file mode 100644 index 00000000..98300b8c --- /dev/null +++ b/test/src/models/template_function_list_test.dart @@ -0,0 +1,20 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('TemplateFunctionList', () { + + test('model', () { + final model = TemplateFunctionList( + total: 5, + templates: [], + ); + + final map = model.toMap(); + final result = TemplateFunctionList.fromMap(map); + + expect(result.total, 5); + expect(result.templates, []); + }); + }); +} diff --git a/test/src/models/template_function_test.dart b/test/src/models/template_function_test.dart new file mode 100644 index 00000000..e1e94cfe --- /dev/null +++ b/test/src/models/template_function_test.dart @@ -0,0 +1,50 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('TemplateFunction', () { + + test('model', () { + final model = TemplateFunction( + icon: 'icon-lightning-bolt', + id: 'starter', + name: 'Starter function', + tagline: 'A simple function to get started.', + permissions: [], + events: [], + cron: '0 0 * * *', + timeout: 300, + useCases: [], + runtimes: [], + instructions: 'For documentation and instructions check out .', + vcsProvider: 'github', + providerRepositoryId: 'templates', + providerOwner: 'appwrite', + providerVersion: 'main', + variables: [], + scopes: [], + ); + + final map = model.toMap(); + final result = TemplateFunction.fromMap(map); + + expect(result.icon, 'icon-lightning-bolt'); + expect(result.id, 'starter'); + expect(result.name, 'Starter function'); + expect(result.tagline, 'A simple function to get started.'); + expect(result.permissions, []); + expect(result.events, []); + expect(result.cron, '0 0 * * *'); + expect(result.timeout, 300); + expect(result.useCases, []); + expect(result.runtimes, []); + expect(result.instructions, 'For documentation and instructions check out .'); + expect(result.vcsProvider, 'github'); + expect(result.providerRepositoryId, 'templates'); + expect(result.providerOwner, 'appwrite'); + expect(result.providerVersion, 'main'); + expect(result.variables, []); + expect(result.scopes, []); + }); + }); +} diff --git a/test/src/models/template_runtime_test.dart b/test/src/models/template_runtime_test.dart new file mode 100644 index 00000000..cea1e41d --- /dev/null +++ b/test/src/models/template_runtime_test.dart @@ -0,0 +1,24 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('TemplateRuntime', () { + + test('model', () { + final model = TemplateRuntime( + name: 'node-19.0', + commands: 'npm install', + entrypoint: 'index.js', + providerRootDirectory: 'node/starter', + ); + + final map = model.toMap(); + final result = TemplateRuntime.fromMap(map); + + expect(result.name, 'node-19.0'); + expect(result.commands, 'npm install'); + expect(result.entrypoint, 'index.js'); + expect(result.providerRootDirectory, 'node/starter'); + }); + }); +} diff --git a/test/src/models/template_variable_test.dart b/test/src/models/template_variable_test.dart new file mode 100644 index 00000000..9da0fdfb --- /dev/null +++ b/test/src/models/template_variable_test.dart @@ -0,0 +1,28 @@ +import 'package:appwrite/models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('TemplateVariable', () { + + test('model', () { + final model = TemplateVariable( + name: 'APPWRITE_DATABASE_ID', + description: 'The ID of the Appwrite database that contains the collection to sync.', + value: '512', + placeholder: '64a55...7b912', + xrequired: true, + type: 'password', + ); + + final map = model.toMap(); + final result = TemplateVariable.fromMap(map); + + expect(result.name, 'APPWRITE_DATABASE_ID'); + expect(result.description, 'The ID of the Appwrite database that contains the collection to sync.'); + expect(result.value, '512'); + expect(result.placeholder, '64a55...7b912'); + expect(result.xrequired, true); + expect(result.type, 'password'); + }); + }); +} From 4b1ab456cdb74814671b4b0e8152a60382e4aef5 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Sat, 17 Aug 2024 08:52:13 +0000 Subject: [PATCH 04/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 310 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5140 insertions(+), 4744 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index ccaa6f63..5313c300 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,148 +3,168 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - - - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt, + Function(UploadProgress)? onProgress}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index d5648d3b..2c708936 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f724282b..15d70b12 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0-rc.2', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index b47292ab..389acea8 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -33,7 +33,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); if (_websok == null) { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From d79226be196805ced22d92ba2dcddd77fa93dbd9 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 19 Aug 2024 09:45:05 +0000 Subject: [PATCH 05/30] chore: update RC version --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 310 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 83 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 4790 insertions(+), 5175 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 5313c300..ccaa6f63 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,168 +3,148 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt, - Function(UploadProgress)? onProgress}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + + + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 2c708936..d5648d3b 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 15d70b12..f724282b 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0-rc.2', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index 389acea8..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -23,6 +23,8 @@ mixin RealtimeMixin { int? get closeCode => _websok?.closeCode; Map _subscriptions = {}; bool _notifyDone = true; + bool _reconnect = true; + int _retries = 0; StreamSubscription? _websocketSubscription; bool _creatingSocket = false; @@ -30,29 +32,31 @@ mixin RealtimeMixin { await _websocketSubscription?.cancel(); await _websok?.sink.close(status.normalClosure, 'Ending session'); _lastUrl = null; + _retries = 0; + _reconnect = false; } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); - if (_websok == null) { - _websok = await getWebSocket(uri); - _lastUrl = uri.toString(); - } else { - if (_lastUrl == uri.toString() && _websok?.closeCode == null) { - _creatingSocket = false; - return; - } - _notifyDone = false; - await _closeConnection(); - _lastUrl = uri.toString(); - _websok = await getWebSocket(uri); - _notifyDone = true; - } - debugPrint('subscription: $_lastUrl'); - try { + if (_websok == null || _websok?.closeCode != null) { + _websok = await getWebSocket(uri); + _lastUrl = uri.toString(); + } else { + if (_lastUrl == uri.toString() && _websok?.closeCode == null) { + _creatingSocket = false; + return; + } + _notifyDone = false; + await _closeConnection(); + _lastUrl = uri.toString(); + _websok = await getWebSocket(uri); + _notifyDone = true; + } + debugPrint('subscription: $_lastUrl'); + _retries = 0; _websocketSubscription = _websok?.stream.listen((response) { final data = RealtimeResponse.fromJson(response); switch (data.type) { @@ -87,34 +91,44 @@ mixin RealtimeMixin { break; } }, onDone: () { - final subscriptions = List.from(_subscriptions.values); - for (var subscription in subscriptions) { - subscription.close(); - } - _channels.clear(); - _closeConnection(); + _retry(); }, onError: (err, stack) { for (var subscription in _subscriptions.values) { subscription.controller.addError(err, stack); } - if (_websok?.closeCode != null && _websok?.closeCode != 1008) { - debugPrint("Reconnecting in one second."); - Future.delayed(Duration(seconds: 1), _createSocket); - } + _retry(); }); } catch (e) { if (e is AppwriteException) { rethrow; } - if (e is WebSocketChannelException) { - throw AppwriteException(e.message); - } - throw AppwriteException(e.toString()); + debugPrint(e.toString()); + _retry(); } finally { _creatingSocket = false; } } + void _retry() async { + if (!_reconnect || _websok?.closeCode == status.policyViolation) { + _reconnect = true; + return; + } + _retries++; + debugPrint("Reconnecting in ${_getTimeout()} seconds."); + Future.delayed(Duration(seconds: _getTimeout()), _createSocket); + } + + int _getTimeout() { + return _retries < 5 + ? 1 + : _retries < 15 + ? 5 + : _retries < 100 + ? 10 + : 60; + } + Uri _prepareUri() { if (client.endPointRealtime == null) { throw AppwriteException( @@ -167,13 +181,10 @@ mixin RealtimeMixin { } void handleError(RealtimeResponse response) { - if (response.data['code'] == 1008) { + if (response.data['code'] == status.policyViolation) { throw AppwriteException(response.data["message"], response.data["code"]); } else { - debugPrint("Reconnecting in one second."); - Future.delayed(const Duration(seconds: 1), () { - _createSocket(); - }); + _retry(); } } } diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 9ae5901001931c54279206c7edf866aaaab0c0f5 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Mon, 19 Aug 2024 09:45:33 +0000 Subject: [PATCH 06/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 310 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5140 insertions(+), 4744 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index ccaa6f63..5313c300 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,148 +3,168 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - - - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt, + Function(UploadProgress)? onProgress}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index d5648d3b..2c708936 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f724282b..15d70b12 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0-rc.2', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From a966e39d8d0f28e159feddeac145daf5d86886ae Mon Sep 17 00:00:00 2001 From: root Date: Tue, 20 Aug 2024 11:01:46 +0000 Subject: [PATCH 07/30] chore: update SDKs to new RC version --- README.md | 2 +- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 300 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 16 +- lib/src/client_io.dart | 76 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- pubspec.yaml | 2 +- test/services/functions_test.dart | 8 +- 92 files changed, 4740 insertions(+), 5150 deletions(-) diff --git a/README.md b/README.md index e8b07298..7c9c829d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^13.0.0-rc.2 + appwrite: ^13.0.0-rc.3 ``` You can install packages from the command line: diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 5313c300..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,168 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt, - Function(UploadProgress)? onProgress}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 2c708936..72b7145f 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -43,7 +43,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.2', + 'x-sdk-version': '13.0.0-rc.3', 'X-Appwrite-Response-Format': '1.6.0', }; @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 15d70b12..f723b805 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,8 +64,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.2', - 'X-Appwrite-Response-Format': '1.6.0', + 'x-sdk-version': '13.0.0-rc.3', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override diff --git a/pubspec.yaml b/pubspec.yaml index 5cb048f7..4a702d47 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 13.0.0-rc.2 +version: 13.0.0-rc.3 description: Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 96a8736d..3ce28c88 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -157,12 +157,8 @@ void main() { 'duration': 0.4,}; - when(client.chunkedUpload( - path: argThat(isNotNull), - params: argThat(isNotNull), - paramName: argThat(isNotNull), - idParamName: argThat(isNotNull), - headers: argThat(isNotNull), + when(client.call( + HttpMethod.post, )).thenAnswer((_) async => Response(data: data)); From f00863d5f757a75d63aa7fe53581ef973be28e6c Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Tue, 20 Aug 2024 11:03:08 +0000 Subject: [PATCH 08/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 72b7145f..218be0ed 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index f723b805..c3632fa7 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0-rc.3', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From cffb8ffa1f5179672ecbfe4dcba6da1d4fb4260e Mon Sep 17 00:00:00 2001 From: root Date: Fri, 23 Aug 2024 10:48:28 +0000 Subject: [PATCH 09/30] chore: updates for next rc release --- README.md | 2 +- .../account/create-anonymous-session.md | 2 +- .../account/create-email-password-session.md | 2 +- docs/examples/account/create-email-token.md | 2 +- docs/examples/account/create-j-w-t.md | 2 +- .../account/create-magic-u-r-l-token.md | 2 +- .../account/create-mfa-authenticator.md | 2 +- docs/examples/account/create-mfa-challenge.md | 2 +- .../account/create-mfa-recovery-codes.md | 2 +- .../examples/account/create-o-auth2session.md | 2 +- docs/examples/account/create-o-auth2token.md | 2 +- docs/examples/account/create-phone-token.md | 2 +- .../account/create-phone-verification.md | 2 +- docs/examples/account/create-push-target.md | 2 +- docs/examples/account/create-recovery.md | 2 +- docs/examples/account/create-session.md | 2 +- docs/examples/account/create-verification.md | 2 +- docs/examples/account/create.md | 2 +- docs/examples/account/delete-identity.md | 2 +- .../account/delete-mfa-authenticator.md | 2 +- docs/examples/account/delete-push-target.md | 2 +- docs/examples/account/delete-session.md | 2 +- docs/examples/account/delete-sessions.md | 2 +- .../account/get-mfa-recovery-codes.md | 2 +- docs/examples/account/get-prefs.md | 2 +- docs/examples/account/get-session.md | 2 +- docs/examples/account/get.md | 2 +- docs/examples/account/list-identities.md | 2 +- docs/examples/account/list-logs.md | 2 +- docs/examples/account/list-mfa-factors.md | 2 +- docs/examples/account/list-sessions.md | 2 +- docs/examples/account/update-email.md | 2 +- docs/examples/account/update-m-f-a.md | 2 +- .../account/update-magic-u-r-l-session.md | 2 +- .../account/update-mfa-authenticator.md | 2 +- docs/examples/account/update-mfa-challenge.md | 2 +- .../account/update-mfa-recovery-codes.md | 2 +- docs/examples/account/update-name.md | 2 +- docs/examples/account/update-password.md | 2 +- docs/examples/account/update-phone-session.md | 2 +- .../account/update-phone-verification.md | 2 +- docs/examples/account/update-phone.md | 2 +- docs/examples/account/update-prefs.md | 2 +- docs/examples/account/update-push-target.md | 2 +- docs/examples/account/update-recovery.md | 2 +- docs/examples/account/update-session.md | 2 +- docs/examples/account/update-status.md | 2 +- docs/examples/account/update-verification.md | 2 +- docs/examples/avatars/get-browser.md | 2 +- docs/examples/avatars/get-credit-card.md | 2 +- docs/examples/avatars/get-favicon.md | 2 +- docs/examples/avatars/get-flag.md | 2 +- docs/examples/avatars/get-image.md | 2 +- docs/examples/avatars/get-initials.md | 2 +- docs/examples/avatars/get-q-r.md | 2 +- docs/examples/databases/create-document.md | 2 +- docs/examples/databases/delete-document.md | 2 +- docs/examples/databases/get-document.md | 2 +- docs/examples/databases/list-documents.md | 2 +- docs/examples/databases/update-document.md | 2 +- docs/examples/functions/create-execution.md | 2 +- .../functions/get-deployment-download.md | 2 +- docs/examples/functions/get-execution.md | 2 +- docs/examples/functions/get-template.md | 2 +- docs/examples/functions/list-executions.md | 2 +- docs/examples/functions/list-templates.md | 2 +- docs/examples/graphql/mutation.md | 2 +- docs/examples/graphql/query.md | 2 +- docs/examples/locale/get.md | 2 +- docs/examples/locale/list-codes.md | 2 +- docs/examples/locale/list-continents.md | 2 +- docs/examples/locale/list-countries-e-u.md | 2 +- docs/examples/locale/list-countries-phones.md | 2 +- docs/examples/locale/list-countries.md | 2 +- docs/examples/locale/list-currencies.md | 2 +- docs/examples/locale/list-languages.md | 2 +- docs/examples/messaging/create-subscriber.md | 2 +- docs/examples/messaging/delete-subscriber.md | 2 +- docs/examples/storage/create-file.md | 2 +- docs/examples/storage/delete-file.md | 2 +- docs/examples/storage/get-file-download.md | 2 +- docs/examples/storage/get-file-preview.md | 2 +- docs/examples/storage/get-file-view.md | 2 +- docs/examples/storage/get-file.md | 2 +- docs/examples/storage/list-files.md | 2 +- docs/examples/storage/update-file.md | 2 +- docs/examples/teams/create-membership.md | 2 +- docs/examples/teams/create.md | 2 +- docs/examples/teams/delete-membership.md | 2 +- docs/examples/teams/delete.md | 2 +- docs/examples/teams/get-membership.md | 2 +- docs/examples/teams/get-prefs.md | 2 +- docs/examples/teams/get.md | 2 +- docs/examples/teams/list-memberships.md | 2 +- docs/examples/teams/list.md | 2 +- .../teams/update-membership-status.md | 2 +- docs/examples/teams/update-membership.md | 2 +- docs/examples/teams/update-name.md | 2 +- docs/examples/teams/update-prefs.md | 2 +- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++--------- lib/services/avatars.dart | 392 ++- lib/services/databases.dart | 259 +- lib/services/functions.dart | 292 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++-- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 16 +- lib/src/client_io.dart | 76 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- pubspec.yaml | 2 +- 189 files changed, 4836 insertions(+), 5234 deletions(-) diff --git a/README.md b/README.md index 7c9c829d..c861aaf8 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^13.0.0-rc.3 + appwrite: ^13.0.0-rc.4 ``` You can install packages from the command line: diff --git a/docs/examples/account/create-anonymous-session.md b/docs/examples/account/create-anonymous-session.md index 173b07af..50887f10 100644 --- a/docs/examples/account/create-anonymous-session.md +++ b/docs/examples/account/create-anonymous-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index 6b498790..64c0e93c 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-email-token.md b/docs/examples/account/create-email-token.md index 497d91a4..140689a9 100644 --- a/docs/examples/account/create-email-token.md +++ b/docs/examples/account/create-email-token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-j-w-t.md b/docs/examples/account/create-j-w-t.md index 5af6e3d3..256f28e0 100644 --- a/docs/examples/account/create-j-w-t.md +++ b/docs/examples/account/create-j-w-t.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-magic-u-r-l-token.md b/docs/examples/account/create-magic-u-r-l-token.md index 8ac49e82..cf2d1bd1 100644 --- a/docs/examples/account/create-magic-u-r-l-token.md +++ b/docs/examples/account/create-magic-u-r-l-token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-mfa-authenticator.md b/docs/examples/account/create-mfa-authenticator.md index 4ea79898..2b35cc9e 100644 --- a/docs/examples/account/create-mfa-authenticator.md +++ b/docs/examples/account/create-mfa-authenticator.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-mfa-challenge.md b/docs/examples/account/create-mfa-challenge.md index bbd95ea7..ad1b8c20 100644 --- a/docs/examples/account/create-mfa-challenge.md +++ b/docs/examples/account/create-mfa-challenge.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-mfa-recovery-codes.md b/docs/examples/account/create-mfa-recovery-codes.md index aa3b78b1..22b3b44c 100644 --- a/docs/examples/account/create-mfa-recovery-codes.md +++ b/docs/examples/account/create-mfa-recovery-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-o-auth2session.md b/docs/examples/account/create-o-auth2session.md index 2679f9eb..d00a1c71 100644 --- a/docs/examples/account/create-o-auth2session.md +++ b/docs/examples/account/create-o-auth2session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-o-auth2token.md b/docs/examples/account/create-o-auth2token.md index 4f62b811..b1478bf9 100644 --- a/docs/examples/account/create-o-auth2token.md +++ b/docs/examples/account/create-o-auth2token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-phone-token.md b/docs/examples/account/create-phone-token.md index 5a096ceb..08dce5f7 100644 --- a/docs/examples/account/create-phone-token.md +++ b/docs/examples/account/create-phone-token.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-phone-verification.md b/docs/examples/account/create-phone-verification.md index f80bbaad..727cfe50 100644 --- a/docs/examples/account/create-phone-verification.md +++ b/docs/examples/account/create-phone-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-push-target.md b/docs/examples/account/create-push-target.md index 33a98cf7..de324b84 100644 --- a/docs/examples/account/create-push-target.md +++ b/docs/examples/account/create-push-target.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-recovery.md b/docs/examples/account/create-recovery.md index 70c52faa..09d0994d 100644 --- a/docs/examples/account/create-recovery.md +++ b/docs/examples/account/create-recovery.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-session.md b/docs/examples/account/create-session.md index b8170cc1..e35cc197 100644 --- a/docs/examples/account/create-session.md +++ b/docs/examples/account/create-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create-verification.md b/docs/examples/account/create-verification.md index 99ba3cbe..85142abe 100644 --- a/docs/examples/account/create-verification.md +++ b/docs/examples/account/create-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/create.md b/docs/examples/account/create.md index 324d0d99..98f6fcba 100644 --- a/docs/examples/account/create.md +++ b/docs/examples/account/create.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-identity.md b/docs/examples/account/delete-identity.md index ae5cd50d..9846a0c1 100644 --- a/docs/examples/account/delete-identity.md +++ b/docs/examples/account/delete-identity.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-mfa-authenticator.md b/docs/examples/account/delete-mfa-authenticator.md index 66a0e897..6d2a21ce 100644 --- a/docs/examples/account/delete-mfa-authenticator.md +++ b/docs/examples/account/delete-mfa-authenticator.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-push-target.md b/docs/examples/account/delete-push-target.md index d80c97ec..f6ec230d 100644 --- a/docs/examples/account/delete-push-target.md +++ b/docs/examples/account/delete-push-target.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-session.md b/docs/examples/account/delete-session.md index 5bf98115..07978e2c 100644 --- a/docs/examples/account/delete-session.md +++ b/docs/examples/account/delete-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index c00d2856..faafcb97 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get-mfa-recovery-codes.md b/docs/examples/account/get-mfa-recovery-codes.md index f4e99b6e..413fb059 100644 --- a/docs/examples/account/get-mfa-recovery-codes.md +++ b/docs/examples/account/get-mfa-recovery-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get-prefs.md b/docs/examples/account/get-prefs.md index 2790e097..bc7731da 100644 --- a/docs/examples/account/get-prefs.md +++ b/docs/examples/account/get-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get-session.md b/docs/examples/account/get-session.md index 0be63f72..4958fd1c 100644 --- a/docs/examples/account/get-session.md +++ b/docs/examples/account/get-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/get.md b/docs/examples/account/get.md index 0bd26c02..c38dd7f4 100644 --- a/docs/examples/account/get.md +++ b/docs/examples/account/get.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-identities.md b/docs/examples/account/list-identities.md index 758b054b..183d525b 100644 --- a/docs/examples/account/list-identities.md +++ b/docs/examples/account/list-identities.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-logs.md b/docs/examples/account/list-logs.md index 7a4ac11a..ec29b951 100644 --- a/docs/examples/account/list-logs.md +++ b/docs/examples/account/list-logs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-mfa-factors.md b/docs/examples/account/list-mfa-factors.md index d66e8862..bb320225 100644 --- a/docs/examples/account/list-mfa-factors.md +++ b/docs/examples/account/list-mfa-factors.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 4c363ccf..3af2299e 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-email.md b/docs/examples/account/update-email.md index 2b5b73ec..b3c7ffe9 100644 --- a/docs/examples/account/update-email.md +++ b/docs/examples/account/update-email.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-m-f-a.md b/docs/examples/account/update-m-f-a.md index 5f65b7e9..c376c729 100644 --- a/docs/examples/account/update-m-f-a.md +++ b/docs/examples/account/update-m-f-a.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-magic-u-r-l-session.md b/docs/examples/account/update-magic-u-r-l-session.md index 0f584d75..e75aba3f 100644 --- a/docs/examples/account/update-magic-u-r-l-session.md +++ b/docs/examples/account/update-magic-u-r-l-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-mfa-authenticator.md b/docs/examples/account/update-mfa-authenticator.md index 9fb8f54c..d2d974fb 100644 --- a/docs/examples/account/update-mfa-authenticator.md +++ b/docs/examples/account/update-mfa-authenticator.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-mfa-challenge.md b/docs/examples/account/update-mfa-challenge.md index 6eac3466..c8e1af7e 100644 --- a/docs/examples/account/update-mfa-challenge.md +++ b/docs/examples/account/update-mfa-challenge.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-mfa-recovery-codes.md b/docs/examples/account/update-mfa-recovery-codes.md index 29c0cff2..fd2aaf72 100644 --- a/docs/examples/account/update-mfa-recovery-codes.md +++ b/docs/examples/account/update-mfa-recovery-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-name.md b/docs/examples/account/update-name.md index bf8048d0..77e774c7 100644 --- a/docs/examples/account/update-name.md +++ b/docs/examples/account/update-name.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-password.md b/docs/examples/account/update-password.md index 0e410601..8d36c1f6 100644 --- a/docs/examples/account/update-password.md +++ b/docs/examples/account/update-password.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-phone-session.md b/docs/examples/account/update-phone-session.md index 1ea87ddf..64d8d842 100644 --- a/docs/examples/account/update-phone-session.md +++ b/docs/examples/account/update-phone-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-phone-verification.md b/docs/examples/account/update-phone-verification.md index d6681a63..5c67e1a5 100644 --- a/docs/examples/account/update-phone-verification.md +++ b/docs/examples/account/update-phone-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-phone.md b/docs/examples/account/update-phone.md index 0e530464..6c9559db 100644 --- a/docs/examples/account/update-phone.md +++ b/docs/examples/account/update-phone.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-prefs.md b/docs/examples/account/update-prefs.md index 15d3a8f5..ca9b709a 100644 --- a/docs/examples/account/update-prefs.md +++ b/docs/examples/account/update-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-push-target.md b/docs/examples/account/update-push-target.md index 78d1b792..a54b1aa3 100644 --- a/docs/examples/account/update-push-target.md +++ b/docs/examples/account/update-push-target.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-recovery.md b/docs/examples/account/update-recovery.md index d12c24d3..648d25b1 100644 --- a/docs/examples/account/update-recovery.md +++ b/docs/examples/account/update-recovery.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-session.md b/docs/examples/account/update-session.md index bb600667..2cdf32aa 100644 --- a/docs/examples/account/update-session.md +++ b/docs/examples/account/update-session.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-status.md b/docs/examples/account/update-status.md index da59e537..0b0fb95e 100644 --- a/docs/examples/account/update-status.md +++ b/docs/examples/account/update-status.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/account/update-verification.md b/docs/examples/account/update-verification.md index 98174f9f..3071a040 100644 --- a/docs/examples/account/update-verification.md +++ b/docs/examples/account/update-verification.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Account account = Account(client); diff --git a/docs/examples/avatars/get-browser.md b/docs/examples/avatars/get-browser.md index 20b039a3..21dae211 100644 --- a/docs/examples/avatars/get-browser.md +++ b/docs/examples/avatars/get-browser.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-credit-card.md b/docs/examples/avatars/get-credit-card.md index 9f645f40..a580e3bd 100644 --- a/docs/examples/avatars/get-credit-card.md +++ b/docs/examples/avatars/get-credit-card.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-favicon.md b/docs/examples/avatars/get-favicon.md index b4003ee0..f35f5a71 100644 --- a/docs/examples/avatars/get-favicon.md +++ b/docs/examples/avatars/get-favicon.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-flag.md b/docs/examples/avatars/get-flag.md index 9751ae23..8f358261 100644 --- a/docs/examples/avatars/get-flag.md +++ b/docs/examples/avatars/get-flag.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-image.md b/docs/examples/avatars/get-image.md index 4c140418..5d8a9865 100644 --- a/docs/examples/avatars/get-image.md +++ b/docs/examples/avatars/get-image.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index c7df00f1..26302d02 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/avatars/get-q-r.md b/docs/examples/avatars/get-q-r.md index fa4c3f41..40f0b506 100644 --- a/docs/examples/avatars/get-q-r.md +++ b/docs/examples/avatars/get-q-r.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Avatars avatars = Avatars(client); diff --git a/docs/examples/databases/create-document.md b/docs/examples/databases/create-document.md index 7970d033..7853329a 100644 --- a/docs/examples/databases/create-document.md +++ b/docs/examples/databases/create-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/delete-document.md b/docs/examples/databases/delete-document.md index 138a5aeb..14cec01c 100644 --- a/docs/examples/databases/delete-document.md +++ b/docs/examples/databases/delete-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/get-document.md b/docs/examples/databases/get-document.md index 7cdd4b04..55206357 100644 --- a/docs/examples/databases/get-document.md +++ b/docs/examples/databases/get-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/list-documents.md b/docs/examples/databases/list-documents.md index ec23cf0e..e78a02de 100644 --- a/docs/examples/databases/list-documents.md +++ b/docs/examples/databases/list-documents.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/databases/update-document.md b/docs/examples/databases/update-document.md index b4179209..29ee8781 100644 --- a/docs/examples/databases/update-document.md +++ b/docs/examples/databases/update-document.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Databases databases = Databases(client); diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index d53f4bf9..94f0ae55 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/functions/get-deployment-download.md b/docs/examples/functions/get-deployment-download.md index c6bda7d4..bb0ee903 100644 --- a/docs/examples/functions/get-deployment-download.md +++ b/docs/examples/functions/get-deployment-download.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/functions/get-execution.md b/docs/examples/functions/get-execution.md index 84747806..b4595146 100644 --- a/docs/examples/functions/get-execution.md +++ b/docs/examples/functions/get-execution.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/functions/get-template.md b/docs/examples/functions/get-template.md index f08ec612..560a4d94 100644 --- a/docs/examples/functions/get-template.md +++ b/docs/examples/functions/get-template.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/functions/list-executions.md b/docs/examples/functions/list-executions.md index a99078ce..ba4b4e41 100644 --- a/docs/examples/functions/list-executions.md +++ b/docs/examples/functions/list-executions.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/functions/list-templates.md b/docs/examples/functions/list-templates.md index bb14efc8..d3d8c7aa 100644 --- a/docs/examples/functions/list-templates.md +++ b/docs/examples/functions/list-templates.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Functions functions = Functions(client); diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index bde93e50..1ac9ba0a 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Graphql graphql = Graphql(client); diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index 35088d91..2c06a838 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Graphql graphql = Graphql(client); diff --git a/docs/examples/locale/get.md b/docs/examples/locale/get.md index 81ca1229..53cfda5c 100644 --- a/docs/examples/locale/get.md +++ b/docs/examples/locale/get.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index 5b6d9755..bfd53f97 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index c4a4ef85..c462c2e4 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-countries-e-u.md b/docs/examples/locale/list-countries-e-u.md index eee42941..0f5629b5 100644 --- a/docs/examples/locale/list-countries-e-u.md +++ b/docs/examples/locale/list-countries-e-u.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index 5136d62a..ee8689a9 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index c3eed1ec..0c1bae60 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index e2300b4e..a9c53b12 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index 83284e2f..c5bdd264 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Locale locale = Locale(client); diff --git a/docs/examples/messaging/create-subscriber.md b/docs/examples/messaging/create-subscriber.md index 85822f8e..1284151b 100644 --- a/docs/examples/messaging/create-subscriber.md +++ b/docs/examples/messaging/create-subscriber.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Messaging messaging = Messaging(client); diff --git a/docs/examples/messaging/delete-subscriber.md b/docs/examples/messaging/delete-subscriber.md index 8551b2ef..aa66acbf 100644 --- a/docs/examples/messaging/delete-subscriber.md +++ b/docs/examples/messaging/delete-subscriber.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Messaging messaging = Messaging(client); diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 77468915..1a0a498b 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -3,7 +3,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/delete-file.md b/docs/examples/storage/delete-file.md index 5e2525ea..39135824 100644 --- a/docs/examples/storage/delete-file.md +++ b/docs/examples/storage/delete-file.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file-download.md b/docs/examples/storage/get-file-download.md index d8d18aa4..33464425 100644 --- a/docs/examples/storage/get-file-download.md +++ b/docs/examples/storage/get-file-download.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index 09c8ddae..2bb09976 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file-view.md b/docs/examples/storage/get-file-view.md index 802bfa89..c5f8ea11 100644 --- a/docs/examples/storage/get-file-view.md +++ b/docs/examples/storage/get-file-view.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/get-file.md b/docs/examples/storage/get-file.md index 6127932b..83a32190 100644 --- a/docs/examples/storage/get-file.md +++ b/docs/examples/storage/get-file.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/list-files.md b/docs/examples/storage/list-files.md index a72d279f..d5f8b0b4 100644 --- a/docs/examples/storage/list-files.md +++ b/docs/examples/storage/list-files.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/storage/update-file.md b/docs/examples/storage/update-file.md index 320f24fb..c88355a5 100644 --- a/docs/examples/storage/update-file.md +++ b/docs/examples/storage/update-file.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Storage storage = Storage(client); diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index b59c69c1..04eedde6 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/create.md b/docs/examples/teams/create.md index 2cd7e4b2..1afcbf1c 100644 --- a/docs/examples/teams/create.md +++ b/docs/examples/teams/create.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/delete-membership.md b/docs/examples/teams/delete-membership.md index 6dfe00fd..83c80a27 100644 --- a/docs/examples/teams/delete-membership.md +++ b/docs/examples/teams/delete-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/delete.md b/docs/examples/teams/delete.md index 3f6de53a..5a4d0dba 100644 --- a/docs/examples/teams/delete.md +++ b/docs/examples/teams/delete.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/get-membership.md b/docs/examples/teams/get-membership.md index 120c1294..3ae0844c 100644 --- a/docs/examples/teams/get-membership.md +++ b/docs/examples/teams/get-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/get-prefs.md b/docs/examples/teams/get-prefs.md index a8d41f28..0f93c25a 100644 --- a/docs/examples/teams/get-prefs.md +++ b/docs/examples/teams/get-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/get.md b/docs/examples/teams/get.md index c29cefa4..bcf45530 100644 --- a/docs/examples/teams/get.md +++ b/docs/examples/teams/get.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/list-memberships.md b/docs/examples/teams/list-memberships.md index 98557687..7fc920a2 100644 --- a/docs/examples/teams/list-memberships.md +++ b/docs/examples/teams/list-memberships.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/list.md b/docs/examples/teams/list.md index 3b70d345..75b29554 100644 --- a/docs/examples/teams/list.md +++ b/docs/examples/teams/list.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-membership-status.md b/docs/examples/teams/update-membership-status.md index 4e397747..e08f63ba 100644 --- a/docs/examples/teams/update-membership-status.md +++ b/docs/examples/teams/update-membership-status.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index 93514b96..33e6568d 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-name.md b/docs/examples/teams/update-name.md index 13623107..43d1b0c7 100644 --- a/docs/examples/teams/update-name.md +++ b/docs/examples/teams/update-name.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/docs/examples/teams/update-prefs.md b/docs/examples/teams/update-prefs.md index 071bd951..2a446f08 100644 --- a/docs/examples/teams/update-prefs.md +++ b/docs/examples/teams/update-prefs.md @@ -2,7 +2,7 @@ import 'package:appwrite/appwrite.dart'; Client client = Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('<YOUR_PROJECT_ID>'); // Your project ID + .setProject(''); // Your project ID Teams teams = Teams(client); diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 218be0ed..48f4d929 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -43,7 +43,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.3', + 'x-sdk-version': '13.0.0-rc.4', 'X-Appwrite-Response-Format': '1.6.0', }; @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index c3632fa7..91eaccd3 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,8 +64,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.3', - 'X-Appwrite-Response-Format': '1.6.0', + 'x-sdk-version': '13.0.0-rc.4', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override diff --git a/pubspec.yaml b/pubspec.yaml index 4a702d47..f17da810 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 13.0.0-rc.3 +version: 13.0.0-rc.4 description: Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter From d1caf81779de7b8fbc74700cb82d7024756cc13d Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Fri, 23 Aug 2024 10:48:55 +0000 Subject: [PATCH 10/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 48f4d929..3eda54ad 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 91eaccd3..1387a956 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0-rc.4', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 39032cb3ea3e59eb73b335bff5b02ef0cff04d4f Mon Sep 17 00:00:00 2001 From: root Date: Fri, 23 Aug 2024 15:25:13 +0000 Subject: [PATCH 11/30] chore: update SDKs for appwrite 1.6.0 --- README.md | 2 +- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 292 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 16 +- lib/src/client_io.dart | 76 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- pubspec.yaml | 12 +- 91 files changed, 4743 insertions(+), 5141 deletions(-) diff --git a/README.md b/README.md index c861aaf8..22851cba 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Add this to your package's `pubspec.yaml` file: ```yml dependencies: - appwrite: ^13.0.0-rc.4 + appwrite: ^13.0.0 ``` You can install packages from the command line: diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3eda54ad..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -43,7 +43,7 @@ class ClientBrowser extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.4', + 'x-sdk-version': '13.0.0', 'X-Appwrite-Response-Format': '1.6.0', }; @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index 1387a956..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,8 +64,8 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-name': 'Flutter', 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', - 'x-sdk-version': '13.0.0-rc.4', - 'X-Appwrite-Response-Format': '1.6.0', + 'x-sdk-version': '13.0.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override diff --git a/pubspec.yaml b/pubspec.yaml index f17da810..20102ea9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: appwrite -version: 13.0.0-rc.4 +version: 13.0.0 description: Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API homepage: https://appwrite.io repository: https://github.com/appwrite/sdk-for-flutter @@ -19,13 +19,13 @@ dependencies: flutter: sdk: flutter cookie_jar: ^4.0.8 - device_info_plus: ^10.1.0 + device_info_plus: ^10.1.2 flutter_web_auth_2: ^3.1.2 http: '>=0.13.6 <2.0.0' - package_info_plus: ^8.0.0 - path_provider: ^2.1.3 - web_socket_channel: ^3.0.0 - web: ^0.5.1 + package_info_plus: ^8.0.2 + path_provider: ^2.1.4 + web_socket_channel: ^3.0.1 + web: ^1.0.0 dev_dependencies: path_provider_platform_interface: ^2.1.2 From 1b60ce7b2ebe38c54b2650480ad2d024d0f720cd Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Fri, 23 Aug 2024 15:25:41 +0000 Subject: [PATCH 12/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From e2227696801f5908e053381efd90af3192463457 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 26 Aug 2024 16:32:13 +0000 Subject: [PATCH 13/30] chore: update for appwrite 1.6.x --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 292 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 4734 insertions(+), 5132 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From cac7045c8fc05f5c32aa482cf968bd16b7fd1545 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Mon, 26 Aug 2024 16:32:43 +0000 Subject: [PATCH 14/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From e47944a07cfef623f427da5ba49a82e0a6f7504e Mon Sep 17 00:00:00 2001 From: root Date: Mon, 26 Aug 2024 16:48:20 +0000 Subject: [PATCH 15/30] chore: update team email address --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 292 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 4734 insertions(+), 5132 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 7b13dae6a761bd4be21a5f96b5c2f7203416ab4a Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Mon, 26 Aug 2024 16:48:54 +0000 Subject: [PATCH 16/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 7c9a2e3997365e5b27023e9c13c7ab6f231d36c1 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 26 Aug 2024 16:55:33 +0000 Subject: [PATCH 17/30] chore: update team email --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 292 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 4734 insertions(+), 5132 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 1f07d18ee9a09132ade1d8fbb9f4fa6b344ae8b3 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Mon, 26 Aug 2024 16:56:05 +0000 Subject: [PATCH 18/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From e1cc8455e9f8849bad39f24cbb5744a232420a62 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 27 Aug 2024 08:52:29 +0000 Subject: [PATCH 19/30] feat: updates for Appwrite 1.6 --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 292 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 4734 insertions(+), 5132 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..3e1a5e2f 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,138 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index 4327b99a..dddb2c94 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; + /// Total number of templates documents that matched your query. + final int total; + /// List of templates. + final List templates; - /// List of templates. - final List templates; + TemplateFunctionList({ + required this.total, + required this.templates, + }); - TemplateFunctionList({ - required this.total, - required this.templates, - }); + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From b2d19a8a0702fe9024bb0aea03f3291e0d73ed94 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Tue, 27 Aug 2024 08:52:57 +0000 Subject: [PATCH 20/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++++---------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 292 +-- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 +-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 42 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 89 files changed, 5132 insertions(+), 4734 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 3e1a5e2f..cf407913 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,138 +3,160 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates({List? runtimes, List? useCases, int? limit, int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List function templates + /// + /// List available function templates. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future listTemplates( + {List? runtimes, + List? useCases, + int? limit, + int? offset}) async { + const String apiPath = '/functions/templates'; + + final Map apiParams = { + 'runtimes': runtimes, + 'useCases': useCases, + 'limit': limit, + 'offset': offset, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunctionList.fromMap(res.data); + } + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart index dddb2c94..4327b99a 100644 --- a/lib/src/models/template_function_list.dart +++ b/lib/src/models/template_function_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Function Templates List class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - /// List of templates. - final List templates; + /// Total number of templates documents that matched your query. + final int total; - TemplateFunctionList({ - required this.total, - required this.templates, - }); + /// List of templates. + final List templates; - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from(map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } + TemplateFunctionList({ + required this.total, + required this.templates, + }); - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } + factory TemplateFunctionList.fromMap(Map map) { + return TemplateFunctionList( + total: map['total'], + templates: List.from( + map['templates'].map((p) => TemplateFunction.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "templates": templates.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From d13fe37a57b930c0971bf9786360b5336d7771a8 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 27 Aug 2024 10:53:33 +0000 Subject: [PATCH 21/30] chore: update Appwrite version --- docs/examples/functions/list-templates.md | 14 - lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/models.dart | 1 - lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++--------- lib/services/avatars.dart | 392 ++- lib/services/databases.dart | 259 +- lib/services/functions.dart | 267 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++-- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_function_list.dart | 30 - lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- test/services/functions_test.dart | 17 - .../models/template_function_list_test.dart | 20 - 93 files changed, 4689 insertions(+), 5192 deletions(-) delete mode 100644 docs/examples/functions/list-templates.md delete mode 100644 lib/src/models/template_function_list.dart delete mode 100644 test/src/models/template_function_list_test.dart diff --git a/docs/examples/functions/list-templates.md b/docs/examples/functions/list-templates.md deleted file mode 100644 index d3d8c7aa..00000000 --- a/docs/examples/functions/list-templates.md +++ /dev/null @@ -1,14 +0,0 @@ -import 'package:appwrite/appwrite.dart'; - -Client client = Client() - .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject(''); // Your project ID - -Functions functions = Functions(client); - -TemplateFunctionList result = await functions.listTemplates( - runtimes: [], // optional - useCases: [], // optional - limit: 1, // optional - offset: 0, // optional -); diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/models.dart b/lib/models.dart index df2bb3fc..7056efa0 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -9,7 +9,6 @@ part 'src/models/log_list.dart'; part 'src/models/file_list.dart'; part 'src/models/team_list.dart'; part 'src/models/membership_list.dart'; -part 'src/models/template_function_list.dart'; part 'src/models/execution_list.dart'; part 'src/models/country_list.dart'; part 'src/models/continent_list.dart'; diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index cf407913..57785844 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,160 +3,113 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List function templates - /// - /// List available function templates. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future listTemplates( - {List? runtimes, - List? useCases, - int? limit, - int? offset}) async { - const String apiPath = '/functions/templates'; - - final Map apiParams = { - 'runtimes': runtimes, - 'useCases': useCases, - 'limit': limit, - 'offset': offset, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunctionList.fromMap(res.data); - } - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate({required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload({required String functionId, required String deploymentId}) async { + final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index 8501afb1..c3fcbe40 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + /// Function Template ID. + final String id; + /// Function Template Name. + final String name; + /// Function Template Tagline. + final String tagline; + /// Execution permissions. + final List permissions; + /// Function trigger events. + final List events; + /// Function execution schedult in CRON format. + final String cron; + /// Function execution timeout in seconds. + final int timeout; + /// Function use cases. + final List useCases; + /// List of runtimes that can be used with this template. + final List runtimes; + /// Function Template Instructions. + final String instructions; + /// VCS (Version Control System) Provider. + final String vcsProvider; + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + /// VCS (Version Control System) Owner. + final String providerOwner; + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + /// Function variables. + final List variables; + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_function_list.dart b/lib/src/models/template_function_list.dart deleted file mode 100644 index 4327b99a..00000000 --- a/lib/src/models/template_function_list.dart +++ /dev/null @@ -1,30 +0,0 @@ -part of '../../models.dart'; - -/// Function Templates List -class TemplateFunctionList implements Model { - /// Total number of templates documents that matched your query. - final int total; - - /// List of templates. - final List templates; - - TemplateFunctionList({ - required this.total, - required this.templates, - }); - - factory TemplateFunctionList.fromMap(Map map) { - return TemplateFunctionList( - total: map['total'], - templates: List.from( - map['templates'].map((p) => TemplateFunction.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "templates": templates.map((p) => p.toMap()).toList(), - }; - } -} diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 495f5515..34209d13 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; + /// Runtime Name. + final String name; + /// The build command used to build the deployment. + final String commands; + /// The entrypoint file used to execute the deployment. + final String entrypoint; + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; - /// The build command used to build the deployment. - final String commands; + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); - /// The entrypoint file used to execute the deployment. - final String entrypoint; + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index 7a6aeb0a..df3982c7 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + /// Variable Description. + final String description; + /// Variable Value. + final String value; + /// Variable Placeholder. + final String placeholder; + /// Is the variable required? + final bool xrequired; + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 3ce28c88..5539c4b9 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -54,23 +54,6 @@ void main() { functions = Functions(client); }); - test('test method listTemplates()', () async { - final Map data = { - 'total': 5, - 'templates': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.listTemplates( - ); - expect(response, isA()); - - }); - test('test method getTemplate()', () async { final Map data = { 'icon': 'icon-lightning-bolt', diff --git a/test/src/models/template_function_list_test.dart b/test/src/models/template_function_list_test.dart deleted file mode 100644 index 98300b8c..00000000 --- a/test/src/models/template_function_list_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -import 'package:appwrite/models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('TemplateFunctionList', () { - - test('model', () { - final model = TemplateFunctionList( - total: 5, - templates: [], - ); - - final map = model.toMap(); - final result = TemplateFunctionList.fromMap(map); - - expect(result.total, 5); - expect(result.templates, []); - }); - }); -} From c2ab6757ec09ad74137848edeee52e1a37c435a7 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Tue, 27 Aug 2024 10:54:02 +0000 Subject: [PATCH 22/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 238 ++- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 214 +- lib/src/models/template_runtime.dart | 63 +- lib/src/models/template_variable.dart | 91 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 ++- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 88 files changed, 5081 insertions(+), 4689 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 57785844..6fffdfbb 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,113 +3,131 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate({required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}'.replaceAll('{templateId}', templateId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload({required String functionId, required String deploymentId}) async { - final String apiPath = '/functions/{functionId}/deployments/{deploymentId}/download'.replaceAll('{functionId}', functionId).replaceAll('{deploymentId}', deploymentId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// Get function template + /// + /// Get a function template using ID. You can use template details in + /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) + /// method. + Future getTemplate( + {required String templateId}) async { + final String apiPath = '/functions/templates/{templateId}' + .replaceAll('{templateId}', templateId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TemplateFunction.fromMap(res.data); + } + + /// Download deployment + /// + /// Get a Deployment's contents by its unique ID. This endpoint supports range + /// requests for partial or streaming file download. + Future getDeploymentDownload( + {required String functionId, required String deploymentId}) async { + final String apiPath = + '/functions/{functionId}/deployments/{deploymentId}/download' + .replaceAll('{functionId}', functionId) + .replaceAll('{deploymentId}', deploymentId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart index c3fcbe40..8501afb1 100644 --- a/lib/src/models/template_function.dart +++ b/lib/src/models/template_function.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Template Function class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - /// Function Template ID. - final String id; - /// Function Template Name. - final String name; - /// Function Template Tagline. - final String tagline; - /// Execution permissions. - final List permissions; - /// Function trigger events. - final List events; - /// Function execution schedult in CRON format. - final String cron; - /// Function execution timeout in seconds. - final int timeout; - /// Function use cases. - final List useCases; - /// List of runtimes that can be used with this template. - final List runtimes; - /// Function Template Instructions. - final String instructions; - /// VCS (Version Control System) Provider. - final String vcsProvider; - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - /// VCS (Version Control System) Owner. - final String providerOwner; - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - /// Function variables. - final List variables; - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from(map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from(map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } + /// Function Template Icon. + final String icon; + + /// Function Template ID. + final String id; + + /// Function Template Name. + final String name; + + /// Function Template Tagline. + final String tagline; + + /// Execution permissions. + final List permissions; + + /// Function trigger events. + final List events; + + /// Function execution schedult in CRON format. + final String cron; + + /// Function execution timeout in seconds. + final int timeout; + + /// Function use cases. + final List useCases; + + /// List of runtimes that can be used with this template. + final List runtimes; + + /// Function Template Instructions. + final String instructions; + + /// VCS (Version Control System) Provider. + final String vcsProvider; + + /// VCS (Version Control System) Repository ID + final String providerRepositoryId; + + /// VCS (Version Control System) Owner. + final String providerOwner; + + /// VCS (Version Control System) branch version (tag). + final String providerVersion; + + /// Function variables. + final List variables; + + /// Function scopes. + final List scopes; + + TemplateFunction({ + required this.icon, + required this.id, + required this.name, + required this.tagline, + required this.permissions, + required this.events, + required this.cron, + required this.timeout, + required this.useCases, + required this.runtimes, + required this.instructions, + required this.vcsProvider, + required this.providerRepositoryId, + required this.providerOwner, + required this.providerVersion, + required this.variables, + required this.scopes, + }); + + factory TemplateFunction.fromMap(Map map) { + return TemplateFunction( + icon: map['icon'].toString(), + id: map['id'].toString(), + name: map['name'].toString(), + tagline: map['tagline'].toString(), + permissions: map['permissions'] ?? [], + events: map['events'] ?? [], + cron: map['cron'].toString(), + timeout: map['timeout'], + useCases: map['useCases'] ?? [], + runtimes: List.from( + map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), + instructions: map['instructions'].toString(), + vcsProvider: map['vcsProvider'].toString(), + providerRepositoryId: map['providerRepositoryId'].toString(), + providerOwner: map['providerOwner'].toString(), + providerVersion: map['providerVersion'].toString(), + variables: List.from( + map['variables'].map((p) => TemplateVariable.fromMap(p))), + scopes: map['scopes'] ?? [], + ); + } + + Map toMap() { + return { + "icon": icon, + "id": id, + "name": name, + "tagline": tagline, + "permissions": permissions, + "events": events, + "cron": cron, + "timeout": timeout, + "useCases": useCases, + "runtimes": runtimes.map((p) => p.toMap()).toList(), + "instructions": instructions, + "vcsProvider": vcsProvider, + "providerRepositoryId": providerRepositoryId, + "providerOwner": providerOwner, + "providerVersion": providerVersion, + "variables": variables.map((p) => p.toMap()).toList(), + "scopes": scopes, + }; + } } diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart index 34209d13..495f5515 100644 --- a/lib/src/models/template_runtime.dart +++ b/lib/src/models/template_runtime.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// Template Runtime class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - /// The build command used to build the deployment. - final String commands; - /// The entrypoint file used to execute the deployment. - final String entrypoint; - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; + /// Runtime Name. + final String name; - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); + /// The build command used to build the deployment. + final String commands; - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } + /// The entrypoint file used to execute the deployment. + final String entrypoint; - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } + /// Path to function in VCS (Version Control System) repository + final String providerRootDirectory; + + TemplateRuntime({ + required this.name, + required this.commands, + required this.entrypoint, + required this.providerRootDirectory, + }); + + factory TemplateRuntime.fromMap(Map map) { + return TemplateRuntime( + name: map['name'].toString(), + commands: map['commands'].toString(), + entrypoint: map['entrypoint'].toString(), + providerRootDirectory: map['providerRootDirectory'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "commands": commands, + "entrypoint": entrypoint, + "providerRootDirectory": providerRootDirectory, + }; + } } diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart index df3982c7..7a6aeb0a 100644 --- a/lib/src/models/template_variable.dart +++ b/lib/src/models/template_variable.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Template Variable class TemplateVariable implements Model { - /// Variable Name. - final String name; - /// Variable Description. - final String description; - /// Variable Value. - final String value; - /// Variable Placeholder. - final String placeholder; - /// Is the variable required? - final bool xrequired; - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } + /// Variable Name. + final String name; + + /// Variable Description. + final String description; + + /// Variable Value. + final String value; + + /// Variable Placeholder. + final String placeholder; + + /// Is the variable required? + final bool xrequired; + + /// Variable Type. + final String type; + + TemplateVariable({ + required this.name, + required this.description, + required this.value, + required this.placeholder, + required this.xrequired, + required this.type, + }); + + factory TemplateVariable.fromMap(Map map) { + return TemplateVariable( + name: map['name'].toString(), + description: map['description'].toString(), + value: map['value'].toString(), + placeholder: map['placeholder'].toString(), + xrequired: map['required'], + type: map['type'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "description": description, + "value": value, + "placeholder": placeholder, + "required": xrequired, + "type": type, + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 4e69499e910a8e205d4cc660a099c799c50cba3d Mon Sep 17 00:00:00 2001 From: root Date: Tue, 27 Aug 2024 11:15:23 +0000 Subject: [PATCH 23/30] chore: updates for appwrite 1.6.x --- .../functions/get-deployment-download.md | 29 - docs/examples/functions/get-template.md | 11 - lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/models.dart | 3 - lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 ++++++++--------- lib/services/avatars.dart | 392 ++- lib/services/databases.dart | 259 +- lib/services/functions.dart | 200 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++-- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 +-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/template_function.dart | 121 - lib/src/models/template_runtime.dart | 41 - lib/src/models/template_variable.dart | 53 - lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- test/services/functions_test.dart | 48 - test/src/models/template_function_test.dart | 50 - test/src/models/template_runtime_test.dart | 24 - test/src/models/template_variable_test.dart | 28 - 95 files changed, 4480 insertions(+), 5292 deletions(-) delete mode 100644 docs/examples/functions/get-deployment-download.md delete mode 100644 docs/examples/functions/get-template.md delete mode 100644 lib/src/models/template_function.dart delete mode 100644 lib/src/models/template_runtime.dart delete mode 100644 lib/src/models/template_variable.dart delete mode 100644 test/src/models/template_function_test.dart delete mode 100644 test/src/models/template_runtime_test.dart delete mode 100644 test/src/models/template_variable_test.dart diff --git a/docs/examples/functions/get-deployment-download.md b/docs/examples/functions/get-deployment-download.md deleted file mode 100644 index bb0ee903..00000000 --- a/docs/examples/functions/get-deployment-download.md +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:appwrite/appwrite.dart'; - -Client client = Client() - .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject(''); // Your project ID - -Functions functions = Functions(client); - -// Downloading file -UInt8List bytes = await functions.getDeploymentDownload( - functionId: '', - deploymentId: '', -) - -final file = File('path_to_file/filename.ext'); -file.writeAsBytesSync(bytes); - -// Displaying image preview -FutureBuilder( - future: functions.getDeploymentDownload( - functionId:'' , - deploymentId:'' , -), // Works for both public file and private file, for private files you need to be logged in - builder: (context, snapshot) { - return snapshot.hasData && snapshot.data != null - ? Image.memory(snapshot.data) - : CircularProgressIndicator(); - } -); diff --git a/docs/examples/functions/get-template.md b/docs/examples/functions/get-template.md deleted file mode 100644 index 560a4d94..00000000 --- a/docs/examples/functions/get-template.md +++ /dev/null @@ -1,11 +0,0 @@ -import 'package:appwrite/appwrite.dart'; - -Client client = Client() - .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject(''); // Your project ID - -Functions functions = Functions(client); - -TemplateFunction result = await functions.getTemplate( - templateId: '', -); diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/models.dart b/lib/models.dart index 7056efa0..a6de0d82 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -36,9 +36,6 @@ part 'src/models/locale_code.dart'; part 'src/models/file.dart'; part 'src/models/team.dart'; part 'src/models/membership.dart'; -part 'src/models/template_function.dart'; -part 'src/models/template_runtime.dart'; -part 'src/models/template_variable.dart'; part 'src/models/execution.dart'; part 'src/models/country.dart'; part 'src/models/continent.dart'; diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 6fffdfbb..4ddd6dfe 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,131 +3,75 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// Get function template - /// - /// Get a function template using ID. You can use template details in - /// [createFunction](/docs/references/cloud/server-nodejs/functions#create) - /// method. - Future getTemplate( - {required String templateId}) async { - final String apiPath = '/functions/templates/{templateId}' - .replaceAll('{templateId}', templateId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TemplateFunction.fromMap(res.data); - } - - /// Download deployment - /// - /// Get a Deployment's contents by its unique ID. This endpoint supports range - /// requests for partial or streaming file download. - Future getDeploymentDownload( - {required String functionId, required String deploymentId}) async { - final String apiPath = - '/functions/{functionId}/deployments/{deploymentId}/download' - .replaceAll('{functionId}', functionId) - .replaceAll('{deploymentId}', deploymentId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/template_function.dart b/lib/src/models/template_function.dart deleted file mode 100644 index 8501afb1..00000000 --- a/lib/src/models/template_function.dart +++ /dev/null @@ -1,121 +0,0 @@ -part of '../../models.dart'; - -/// Template Function -class TemplateFunction implements Model { - /// Function Template Icon. - final String icon; - - /// Function Template ID. - final String id; - - /// Function Template Name. - final String name; - - /// Function Template Tagline. - final String tagline; - - /// Execution permissions. - final List permissions; - - /// Function trigger events. - final List events; - - /// Function execution schedult in CRON format. - final String cron; - - /// Function execution timeout in seconds. - final int timeout; - - /// Function use cases. - final List useCases; - - /// List of runtimes that can be used with this template. - final List runtimes; - - /// Function Template Instructions. - final String instructions; - - /// VCS (Version Control System) Provider. - final String vcsProvider; - - /// VCS (Version Control System) Repository ID - final String providerRepositoryId; - - /// VCS (Version Control System) Owner. - final String providerOwner; - - /// VCS (Version Control System) branch version (tag). - final String providerVersion; - - /// Function variables. - final List variables; - - /// Function scopes. - final List scopes; - - TemplateFunction({ - required this.icon, - required this.id, - required this.name, - required this.tagline, - required this.permissions, - required this.events, - required this.cron, - required this.timeout, - required this.useCases, - required this.runtimes, - required this.instructions, - required this.vcsProvider, - required this.providerRepositoryId, - required this.providerOwner, - required this.providerVersion, - required this.variables, - required this.scopes, - }); - - factory TemplateFunction.fromMap(Map map) { - return TemplateFunction( - icon: map['icon'].toString(), - id: map['id'].toString(), - name: map['name'].toString(), - tagline: map['tagline'].toString(), - permissions: map['permissions'] ?? [], - events: map['events'] ?? [], - cron: map['cron'].toString(), - timeout: map['timeout'], - useCases: map['useCases'] ?? [], - runtimes: List.from( - map['runtimes'].map((p) => TemplateRuntime.fromMap(p))), - instructions: map['instructions'].toString(), - vcsProvider: map['vcsProvider'].toString(), - providerRepositoryId: map['providerRepositoryId'].toString(), - providerOwner: map['providerOwner'].toString(), - providerVersion: map['providerVersion'].toString(), - variables: List.from( - map['variables'].map((p) => TemplateVariable.fromMap(p))), - scopes: map['scopes'] ?? [], - ); - } - - Map toMap() { - return { - "icon": icon, - "id": id, - "name": name, - "tagline": tagline, - "permissions": permissions, - "events": events, - "cron": cron, - "timeout": timeout, - "useCases": useCases, - "runtimes": runtimes.map((p) => p.toMap()).toList(), - "instructions": instructions, - "vcsProvider": vcsProvider, - "providerRepositoryId": providerRepositoryId, - "providerOwner": providerOwner, - "providerVersion": providerVersion, - "variables": variables.map((p) => p.toMap()).toList(), - "scopes": scopes, - }; - } -} diff --git a/lib/src/models/template_runtime.dart b/lib/src/models/template_runtime.dart deleted file mode 100644 index 495f5515..00000000 --- a/lib/src/models/template_runtime.dart +++ /dev/null @@ -1,41 +0,0 @@ -part of '../../models.dart'; - -/// Template Runtime -class TemplateRuntime implements Model { - /// Runtime Name. - final String name; - - /// The build command used to build the deployment. - final String commands; - - /// The entrypoint file used to execute the deployment. - final String entrypoint; - - /// Path to function in VCS (Version Control System) repository - final String providerRootDirectory; - - TemplateRuntime({ - required this.name, - required this.commands, - required this.entrypoint, - required this.providerRootDirectory, - }); - - factory TemplateRuntime.fromMap(Map map) { - return TemplateRuntime( - name: map['name'].toString(), - commands: map['commands'].toString(), - entrypoint: map['entrypoint'].toString(), - providerRootDirectory: map['providerRootDirectory'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "commands": commands, - "entrypoint": entrypoint, - "providerRootDirectory": providerRootDirectory, - }; - } -} diff --git a/lib/src/models/template_variable.dart b/lib/src/models/template_variable.dart deleted file mode 100644 index 7a6aeb0a..00000000 --- a/lib/src/models/template_variable.dart +++ /dev/null @@ -1,53 +0,0 @@ -part of '../../models.dart'; - -/// Template Variable -class TemplateVariable implements Model { - /// Variable Name. - final String name; - - /// Variable Description. - final String description; - - /// Variable Value. - final String value; - - /// Variable Placeholder. - final String placeholder; - - /// Is the variable required? - final bool xrequired; - - /// Variable Type. - final String type; - - TemplateVariable({ - required this.name, - required this.description, - required this.value, - required this.placeholder, - required this.xrequired, - required this.type, - }); - - factory TemplateVariable.fromMap(Map map) { - return TemplateVariable( - name: map['name'].toString(), - description: map['description'].toString(), - value: map['value'].toString(), - placeholder: map['placeholder'].toString(), - xrequired: map['required'], - type: map['type'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "description": description, - "value": value, - "placeholder": placeholder, - "required": xrequired, - "type": type, - }; - } -} diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override diff --git a/test/services/functions_test.dart b/test/services/functions_test.dart index 5539c4b9..8707d054 100644 --- a/test/services/functions_test.dart +++ b/test/services/functions_test.dart @@ -54,54 +54,6 @@ void main() { functions = Functions(client); }); - test('test method getTemplate()', () async { - final Map data = { - 'icon': 'icon-lightning-bolt', - 'id': 'starter', - 'name': 'Starter function', - 'tagline': 'A simple function to get started.', - 'permissions': [], - 'events': [], - 'cron': '0 0 * * *', - 'timeout': 300, - 'useCases': [], - 'runtimes': [], - 'instructions': 'For documentation and instructions check out .', - 'vcsProvider': 'github', - 'providerRepositoryId': 'templates', - 'providerOwner': 'appwrite', - 'providerVersion': 'main', - 'variables': [], - 'scopes': [],}; - - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.getTemplate( - templateId: '', - ); - expect(response, isA()); - - }); - - test('test method getDeploymentDownload()', () async {final Uint8List data = Uint8List.fromList([]); - - when(client.call( - HttpMethod.get, - )).thenAnswer((_) async => Response(data: data)); - - - final response = await functions.getDeploymentDownload( - functionId: '', - deploymentId: '', - ); - expect(response, isA()); - - }); - test('test method listExecutions()', () async { final Map data = { 'total': 5, diff --git a/test/src/models/template_function_test.dart b/test/src/models/template_function_test.dart deleted file mode 100644 index e1e94cfe..00000000 --- a/test/src/models/template_function_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -import 'package:appwrite/models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('TemplateFunction', () { - - test('model', () { - final model = TemplateFunction( - icon: 'icon-lightning-bolt', - id: 'starter', - name: 'Starter function', - tagline: 'A simple function to get started.', - permissions: [], - events: [], - cron: '0 0 * * *', - timeout: 300, - useCases: [], - runtimes: [], - instructions: 'For documentation and instructions check out .', - vcsProvider: 'github', - providerRepositoryId: 'templates', - providerOwner: 'appwrite', - providerVersion: 'main', - variables: [], - scopes: [], - ); - - final map = model.toMap(); - final result = TemplateFunction.fromMap(map); - - expect(result.icon, 'icon-lightning-bolt'); - expect(result.id, 'starter'); - expect(result.name, 'Starter function'); - expect(result.tagline, 'A simple function to get started.'); - expect(result.permissions, []); - expect(result.events, []); - expect(result.cron, '0 0 * * *'); - expect(result.timeout, 300); - expect(result.useCases, []); - expect(result.runtimes, []); - expect(result.instructions, 'For documentation and instructions check out .'); - expect(result.vcsProvider, 'github'); - expect(result.providerRepositoryId, 'templates'); - expect(result.providerOwner, 'appwrite'); - expect(result.providerVersion, 'main'); - expect(result.variables, []); - expect(result.scopes, []); - }); - }); -} diff --git a/test/src/models/template_runtime_test.dart b/test/src/models/template_runtime_test.dart deleted file mode 100644 index cea1e41d..00000000 --- a/test/src/models/template_runtime_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:appwrite/models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('TemplateRuntime', () { - - test('model', () { - final model = TemplateRuntime( - name: 'node-19.0', - commands: 'npm install', - entrypoint: 'index.js', - providerRootDirectory: 'node/starter', - ); - - final map = model.toMap(); - final result = TemplateRuntime.fromMap(map); - - expect(result.name, 'node-19.0'); - expect(result.commands, 'npm install'); - expect(result.entrypoint, 'index.js'); - expect(result.providerRootDirectory, 'node/starter'); - }); - }); -} diff --git a/test/src/models/template_variable_test.dart b/test/src/models/template_variable_test.dart deleted file mode 100644 index 9da0fdfb..00000000 --- a/test/src/models/template_variable_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -import 'package:appwrite/models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('TemplateVariable', () { - - test('model', () { - final model = TemplateVariable( - name: 'APPWRITE_DATABASE_ID', - description: 'The ID of the Appwrite database that contains the collection to sync.', - value: '512', - placeholder: '64a55...7b912', - xrequired: true, - type: 'password', - ); - - final map = model.toMap(); - final result = TemplateVariable.fromMap(map); - - expect(result.name, 'APPWRITE_DATABASE_ID'); - expect(result.description, 'The ID of the Appwrite database that contains the collection to sync.'); - expect(result.value, '512'); - expect(result.placeholder, '64a55...7b912'); - expect(result.xrequired, true); - expect(result.type, 'password'); - }); - }); -} From 8cc960c71d23228d0b8134f3b3ff4d1bbcefd7fe Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Tue, 27 Aug 2024 11:16:23 +0000 Subject: [PATCH 24/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 ++- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 85 files changed, 4842 insertions(+), 4480 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 4ddd6dfe..c78d6294 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,75 +3,89 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 254426c56df6752b403c4cae9ecbdb3a8b663d1a Mon Sep 17 00:00:00 2001 From: root Date: Tue, 27 Aug 2024 11:32:27 +0000 Subject: [PATCH 25/30] chore: update sdks for appwrite 1.6 --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +-- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 85 files changed, 4480 insertions(+), 4842 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index c78d6294..4ddd6dfe 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,89 +3,75 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From f3768863a08919ff72bbbdf0c4911b200d783687 Mon Sep 17 00:00:00 2001 From: christyjacob4 Date: Tue, 27 Aug 2024 11:32:53 +0000 Subject: [PATCH 26/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 ++- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 85 files changed, 4842 insertions(+), 4480 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 4ddd6dfe..c78d6294 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,75 +3,89 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 645b3e0353863ea14c7fe74050ce0cc7fd8fbdf9 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Tue, 27 Aug 2024 15:24:52 +0200 Subject: [PATCH 27/30] add changelog --- CHANGELOG.md | 14 + lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +-- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 86 files changed, 4494 insertions(+), 4842 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b729792e..95ac7768 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,17 @@ +## 13.0.0 + +* Fixed realtime reconnection issues +* Support for Appwrite 1.6 +* Update dependencies +* Added `scheduledAt` attribute to `Execution` response model +* Added `scheduledAt` parameter to `createExecution()`: Enables creating a delayed execution +* Breaking changes: + * Removed `otp` parameter from `deleteMFAAuthenticator`. + +You can find the new syntax for breaking changes in the [Appwrite API references](https://appwrite.io/docs/references). Select version `1.6.x`. + +**Please note: This version is compatible with Appwrite 1.6 and later only. If you do not update your Appwrite SDK, old SDKs will not break your app. Appwrite APIs are backwards compatible.** + ## 12.0.4 * Fixed concurrent modification error when closing realtime socket diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index c78d6294..4ddd6dfe 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,89 +3,75 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From b2b1e6d50b1463e403b8b29704999bc696732342 Mon Sep 17 00:00:00 2001 From: TorstenDittmann Date: Tue, 27 Aug 2024 13:25:17 +0000 Subject: [PATCH 28/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 ++- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 85 files changed, 4842 insertions(+), 4480 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 4ddd6dfe..c78d6294 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,75 +3,89 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From b89e914819e55507c26919a5c72451d998a034b6 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Tue, 27 Aug 2024 15:27:12 +0200 Subject: [PATCH 29/30] fix syntax --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 +-- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 +-- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 ++- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 +-- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 85 files changed, 4480 insertions(+), 4842 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index c89bac24..d0c2331e 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index b9805a3a..09f110ea 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; +export 'src/client_browser.dart'; \ No newline at end of file diff --git a/lib/client_io.dart b/lib/client_io.dart index 42a0c0b6..4d85cbfa 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; +export 'src/client_io.dart'; \ No newline at end of file diff --git a/lib/id.dart b/lib/id.dart index 1443ada7..c1d473ce 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,7 +10,8 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index e407f7fe..82d0c544 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,5 +1,6 @@ part of 'appwrite.dart'; + /// Helper class to generate query strings. class Query { final String method; @@ -13,11 +14,11 @@ class Query { 'method': method, }; - if (attribute != null) { + if(attribute != null) { map['attribute'] = attribute; } - - if (values != null) { + + if(values != null) { map['values'] = values is List ? values : [values]; } @@ -28,7 +29,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -60,12 +61,10 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => - Query._('isNull', attribute).toString(); + static String isNull(String attribute) => Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => - Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -85,46 +84,40 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) - .toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => - Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => - Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => - Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => - Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => - Query._('offset', null, offset).toString(); -} + static String offset(int offset) => Query._('offset', null, offset).toString(); + +} \ No newline at end of file diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 05e8456e..5aa5f420 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; +export 'src/realtime_browser.dart'; \ No newline at end of file diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 750cbe20..5f557007 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; +export 'src/realtime_io.dart'; \ No newline at end of file diff --git a/lib/role.dart b/lib/role.dart index 9eae13b6..103f120c 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); + + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if (status.isEmpty) { - return 'user:$id'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if(status.isEmpty) { + return 'user:$id'; + } + return 'user:$id/$status'; } - return 'user:$id/$status'; - } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if (status.isEmpty) { - return 'users'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if(status.isEmpty) { + return 'users'; + } + return 'users/$status'; } - return 'users/$status'; - } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if (role.isEmpty) { - return 'team:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if(role.isEmpty) { + return 'team:$id'; + } + return 'team:$id/$role'; } - return 'team:$id/$role'; - } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; - } + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} \ No newline at end of file diff --git a/lib/services/account.dart b/lib/services/account.dart index a94a37d2..92803ae6 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1194 +2,1163 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create( - {required String userId, - required String email, - required String password, - String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail( - {required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}' - .replaceAll('{identityId}', identityId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator( - {required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator( - {required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = - '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge( - {required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge( - {required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword( - {required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone( - {required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery( - {required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery( - {required String userId, - required String secret, - required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession( - {required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession( - {required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = - '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - } - - /// Create push target - /// - Future createPushTarget( - {required String targetId, - required String identifier, - String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Update push target - /// - Future updatePushTarget( - {required String targetId, required String identifier}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = - '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken( - {required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken( - {required String userId, - required String email, - String? url, - bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token( - {required enums.OAuthProvider provider, - String? success, - String? failure, - List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}' - .replaceAll('{provider}', provider.value); - - final Map params = { - 'success': success, - 'failure': failure, - 'scopes': scopes, - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + - '=' + - Uri.encodeComponent(item)); - } - } else if (value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri( - scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&')); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken( - {required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification( - {required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - } -} + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create({required String userId, required String email, required String password, String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail({required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge({required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword({required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone({required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery({required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery({required String userId, required String secret, required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession({required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession({required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + + } + + /// Create push target + /// + Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Update push target + /// + Future updatePushTarget({required String targetId, required String identifier}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken({required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); + + final Map params = { + + 'success': success, + 'failure': failure, + 'scopes': scopes, + + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); + } + } else if(value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri(scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&') + ); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken({required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification({required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 3bc203e9..144c32a3 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,203 +3,195 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser( - {required enums.Browser code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard( - {required enums.CreditCard code, - int? width, - int? height, - int? quality}) async { - final String apiPath = - '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - 'url': url, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag( - {required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = - '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - 'width': width, - 'height': height, - 'quality': quality, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage( - {required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - 'url': url, - 'width': width, - 'height': height, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials( - {String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - 'name': name, - 'width': width, - 'height': height, - 'background': background, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR( - {required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + + 'url': url, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + + 'width': width, + 'height': height, + 'quality': quality, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage({required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + + 'url': url, + 'width': width, + 'height': height, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials({String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + + 'name': name, + 'width': width, + 'height': height, + 'background': background, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR({required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 36f4a1db..08d3e10b 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,151 +3,114 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments( - {required String databaseId, - required String collectionId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument( - {required String databaseId, - required String collectionId, - required String documentId, - required Map data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument( - {required String databaseId, - required String collectionId, - required String documentId, - List? queries}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument( - {required String databaseId, - required String collectionId, - required String documentId, - Map? data, - List? permissions}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument( - {required String databaseId, - required String collectionId, - required String documentId}) async { - final String apiPath = - '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' - .replaceAll('{databaseId}', databaseId) - .replaceAll('{collectionId}', collectionId) - .replaceAll('{documentId}', documentId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { + final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/functions.dart b/lib/services/functions.dart index c78d6294..4ddd6dfe 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,89 +3,75 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions( - {required String functionId, - List? queries, - String? search}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution( - {required String functionId, - String? body, - bool? xasync, - String? path, - enums.ExecutionMethod? method, - Map? headers, - String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions' - .replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution( - {required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}' - .replaceAll('{functionId}', functionId) - .replaceAll('{executionId}', executionId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - } -} + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions({required String functionId, List? queries, String? search}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution({required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index f653df6c..1e5b32b0 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,48 +3,46 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 6c780391..8be6f074 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,163 +3,171 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); - } + return models.Locale.fromMap(res.data); - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + } - final Map apiParams = {}; + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LocaleCodeList.fromMap(res.data); - } + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + return models.LocaleCodeList.fromMap(res.data); - final Map apiParams = {}; + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = { + }; - return models.ContinentList.fromMap(res.data); - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = {}; + return models.ContinentList.fromMap(res.data); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + } - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.CountryList.fromMap(res.data); - } + final Map apiParams = { + }; - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = {}; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.CountryList.fromMap(res.data); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + } - return models.CountryList.fromMap(res.data); - } + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + final Map apiParams = { + }; - final Map apiParams = {}; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + return models.CountryList.fromMap(res.data); - return models.PhoneList.fromMap(res.data); - } + } - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiParams = {}; + final Map apiParams = { + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - return models.CurrencyList.fromMap(res.data); - } + return models.PhoneList.fromMap(res.data); - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; + } - final Map apiParams = {}; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = { + }; - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.LanguageList.fromMap(res.data); - } -} + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.CurrencyList.fromMap(res.data); + + } + + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LanguageList.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 75a6630c..30b53556 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,53 +3,46 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber( - {required String topicId, - required String subscriberId, - required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers' - .replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber( - {required String topicId, required String subscriberId}) async { - final String apiPath = - '/messaging/topics/{topicId}/subscribers/{subscriberId}' - .replaceAll('{topicId}', topicId) - .replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } -} + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber({required String topicId, required String subscriberId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } +} \ No newline at end of file diff --git a/lib/services/storage.dart b/lib/services/storage.dart index d4ba05a2..be4945cf 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,240 +2,208 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles( - {required String bucketId, List? queries, String? search}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile( - {required String bucketId, - required String fileId, - required InputFile file, - List? permissions, - Function(UploadProgress)? onProgress}) async { - final String apiPath = - '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile( - {required String bucketId, - required String fileId, - String? name, - List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview( - {required String bucketId, - required String fileId, - int? width, - int? height, - enums.ImageGravity? gravity, - int? quality, - int? borderWidth, - String? borderColor, - int? borderRadius, - double? opacity, - int? rotation, - String? background, - enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView( - {required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' - .replaceAll('{bucketId}', bucketId) - .replaceAll('{fileId}', fileId); - - final Map params = { - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles({required String bucketId, List? queries, String? search}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { + final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + + + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); + + final Map params = { + + + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} \ No newline at end of file diff --git a/lib/services/teams.dart b/lib/services/teams.dart index a9c7450d..21f31e07 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,341 +3,312 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create( - {required String teamId, - required String name, - List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName( - {required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships( - {required String teamId, List? queries, String? search}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership( - {required String teamId, - required List roles, - String? email, - String? userId, - String? phone, - String? url, - String? name}) async { - final String apiPath = - '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership( - {required String teamId, - required String membershipId, - required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership( - {required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, - path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus( - {required String teamId, - required String membershipId, - required String userId, - required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' - .replaceAll('{teamId}', teamId) - .replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = {}; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs( - {required String teamId, required Map prefs}) async { - final String apiPath = - '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, - path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - } -} + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create({required String teamId, required String name, List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName({required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships({required String teamId, List? queries, String? search}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { + final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership({required String teamId, required String membershipId, required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership({required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs({required String teamId, required Map prefs}) async { + final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + + } +} \ No newline at end of file diff --git a/lib/src/client.dart b/lib/src/client.dart index 9faffd2f..825e24aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,8 +10,7 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5 * 1024 * 1024; - + static const int CHUNK_SIZE = 5*1024*1024; /// Holds configuration such as project. late Map config; late String _endPoint; @@ -19,7 +18,6 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; - /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -43,7 +41,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -77,8 +75,7 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call( - HttpMethod method, { + Future call(HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index ed751111..f94505ab 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,17 +2,15 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); - /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); - /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 36402189..3bbe39f5 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -64,7 +64,6 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } - /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -72,14 +71,12 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } - @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } - /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -141,8 +138,7 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, - filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); return call( HttpMethod.post, path: path, @@ -169,8 +165,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -230,7 +226,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index cab345ff..afdbda28 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5 * 1024 * 1024; + static const int CHUNK_SIZE = 5*1024*1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format': '1.6.0', + 'X-Appwrite-Response-Format' : '1.6.0', }; config = {}; @@ -86,36 +86,33 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -148,7 +145,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if (_initProgress) return; + if(_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -184,12 +181,13 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader('user-agent', - '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader( + 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader('user-agent', '$device'); + addHeader( + 'user-agent', '$device'); } _initialized = true; @@ -298,8 +296,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, - filename: file.filename); + params[paramName] = + http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 1078c313..36bcdbd3 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value) { + params = params.map((key, value){ if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,23 +106,18 @@ class ClientMixin { return Response(data: data); } - Future toResponse( - http.StreamedResponse streamedResponse) async { - if (streamedResponse.statusCode == 204) { - return http.Response( - '', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k, v) => - k.toLowerCase() == 'content-type' - ? MapEntry(k, 'text/plain') - : MapEntry(k, v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse(http.StreamedResponse streamedResponse) async { + if(streamedResponse.statusCode == 204) { + return http.Response('', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 1d5271eb..00d12830 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,14 +1,16 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({required this.value}); + const AuthenticationFactor({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index c1fe8584..10460393 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,11 +1,13 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({required this.value}); + const AuthenticatorType({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 949f4c47..386fa11d 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,24 +1,26 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({required this.value}); + const Browser({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 3a6b256a..7d54fa80 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,26 +1,28 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({required this.value}); + const CreditCard({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 42954430..7d2d7016 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,16 +1,18 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({required this.value}); + const ExecutionMethod({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index a44cb81d..27c25cac 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,205 +1,207 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({required this.value}); + const Flag({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 2ab5d7b9..66527dfa 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,15 +1,17 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({required this.value}); + const ImageFormat({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 88029044..79bc4d62 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,19 +1,21 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({required this.value}); + const ImageGravity({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index 2bc1a82a..b09e9df2 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,49 +1,51 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({required this.value}); + const OAuthProvider({ + required this.value + }); - final String value; + final String value; - String toJson() => value; -} + String toJson() => value; +} \ No newline at end of file diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 3d608201..2cc8608b 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 4145f701..759f320d 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Memory used to compute hash. + final int memoryCost; + /// Amount of time consumed to compute hash + final int timeCost; + /// Number of threads used to compute hash. + final int threads; - /// Memory used to compute hash. - final int memoryCost; + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); - /// Amount of time consumed to compute hash - final int timeCost; + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } - /// Number of threads used to compute hash. - final int threads; - - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); - - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } - - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index 2ba0c398..c9f67200 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 8bdfca6f..2fabb416 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index 4f5f9179..fdcee07a 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index fec6f65a..5c36373d 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,46 +2,42 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - - /// CPU complexity of computed hash. - final int costCpu; - - /// Memory complexity of computed hash. - final int costMemory; - - /// Parallelization of computed hash. - final int costParallel; - - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + /// CPU complexity of computed hash. + final int costCpu; + /// Memory complexity of computed hash. + final int costMemory; + /// Parallelization of computed hash. + final int costParallel; + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index 0e80700f..b10b14a6 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; + /// Salt used to compute hash. + final String salt; + /// Separator used to compute hash. + final String saltSeparator; + /// Key used to compute hash. + final String signerKey; - /// Salt used to compute hash. - final String salt; + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); - /// Separator used to compute hash. - final String saltSeparator; + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } - /// Key used to compute hash. - final String signerKey; - - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); - - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } - - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 47068be0..5f3e1654 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index 990b1064..e1772f0d 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; + /// Continent name. + final String name; + /// Continent two letter code. + final String code; - /// Continent two letter code. - final String code; + Continent({ + required this.name, + required this.code, + }); - Continent({ - required this.name, - required this.code, - }); + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index fb4ee6f6..d0830aad 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; + /// Total number of continents documents that matched your query. + final int total; + /// List of continents. + final List continents; - /// List of continents. - final List continents; + ContinentList({ + required this.total, + required this.continents, + }); - ContinentList({ - required this.total, - required this.continents, - }); + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), + ); + } - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from( - map['continents'].map((p) => Continent.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index d11c55db..b8757434 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; + /// Country name. + final String name; + /// Country two-character ISO 3166-1 alpha code. + final String code; - /// Country two-character ISO 3166-1 alpha code. - final String code; + Country({ + required this.name, + required this.code, + }); - Country({ - required this.name, - required this.code, - }); + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index a62f926d..7fa08533 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; + /// Total number of countries documents that matched your query. + final int total; + /// List of countries. + final List countries; - /// List of countries. - final List countries; + CountryList({ + required this.total, + required this.countries, + }); - CountryList({ - required this.total, - required this.countries, - }); + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: - List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 27eef0c1..11aba951 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - - /// Currency name. - final String name; - - /// Currency native symbol. - final String symbolNative; - - /// Number of decimal digits. - final int decimalDigits; - - /// Currency digit rounding. - final double rounding; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + /// Currency name. + final String name; + /// Currency native symbol. + final String symbolNative; + /// Number of decimal digits. + final int decimalDigits; + /// Currency digit rounding. + final double rounding; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index e912ca0a..cf925bc5 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; + /// Total number of currencies documents that matched your query. + final int total; + /// List of currencies. + final List currencies; - /// List of currencies. - final List currencies; + CurrencyList({ + required this.total, + required this.currencies, + }); - CurrencyList({ - required this.total, - required this.currencies, - }); + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), + ); + } - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from( - map['currencies'].map((p) => Currency.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index 6406f06a..d5b8c77e 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,58 +2,53 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - - /// Collection ID. - final String $collectionId; - - /// Database ID. - final String $databaseId; - - /// Document creation date in ISO 8601 format. - final String $createdAt; - - /// Document update date in ISO 8601 format. - final String $updatedAt; - - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + /// Collection ID. + final String $collectionId; + /// Database ID. + final String $databaseId; + /// Document creation date in ISO 8601 format. + final String $createdAt; + /// Document update date in ISO 8601 format. + final String $updatedAt; + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index b4fd20eb..9d3de14b 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,32 +2,30 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; + /// Total number of documents documents that matched your query. + final int total; + /// List of documents. + final List documents; - /// List of documents. - final List documents; + DocumentList({ + required this.total, + required this.documents, + }); - DocumentList({ - required this.total, - required this.documents, - }); + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: - List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } - - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 40886cd7..96548ef2 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,120 +2,102 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - - /// Execution creation date in ISO 8601 format. - final String $createdAt; - - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - - /// Execution roles. - final List $permissions; - - /// Function ID. - final String functionId; - - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - - /// HTTP request method type. - final String requestMethod; - - /// HTTP request path and query. - final String requestPath; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - - /// HTTP response status code. - final int responseStatusCode; - - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - - /// Function execution duration in seconds. - final double duration; - - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from( - map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from( - map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + /// Execution creation date in ISO 8601 format. + final String $createdAt; + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + /// Execution roles. + final List $permissions; + /// Function ID. + final String functionId; + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + /// HTTP request method type. + final String requestMethod; + /// HTTP request path and query. + final String requestPath; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + /// HTTP response status code. + final int responseStatusCode; + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + /// Function execution duration in seconds. + final double duration; + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 32e40531..00333204 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; + /// Total number of executions documents that matched your query. + final int total; + /// List of executions. + final List executions; - /// List of executions. - final List executions; + ExecutionList({ + required this.total, + required this.executions, + }); - ExecutionList({ - required this.total, - required this.executions, - }); + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), + ); + } - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from( - map['executions'].map((p) => Execution.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index 2e6b9d8f..a6094782 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,82 +2,72 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; + /// File ID. + final String $id; + /// Bucket ID. + final String bucketId; + /// File creation date in ISO 8601 format. + final String $createdAt; + /// File update date in ISO 8601 format. + final String $updatedAt; + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + /// File name. + final String name; + /// File MD5 signature. + final String signature; + /// File mime type. + final String mimeType; + /// File original size in bytes. + final int sizeOriginal; + /// Total number of chunks available + final int chunksTotal; + /// Total number of chunks uploaded + final int chunksUploaded; - /// Bucket ID. - final String bucketId; + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); - /// File creation date in ISO 8601 format. - final String $createdAt; + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } - /// File update date in ISO 8601 format. - final String $updatedAt; - - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - - /// File name. - final String name; - - /// File MD5 signature. - final String signature; - - /// File mime type. - final String mimeType; - - /// File original size in bytes. - final int sizeOriginal; - - /// Total number of chunks available - final int chunksTotal; - - /// Total number of chunks uploaded - final int chunksUploaded; - - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); - - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } - - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index 3b695c93..b0872489 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; + /// Total number of files documents that matched your query. + final int total; + /// List of files. + final List files; - /// List of files. - final List files; + FileList({ + required this.total, + required this.files, + }); - FileList({ - required this.total, - required this.files, - }); + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index 22494998..f03c5ce4 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; + /// Header name. + final String name; + /// Header value. + final String value; - /// Header value. - final String value; + Headers({ + required this.name, + required this.value, + }); - Headers({ - required this.name, - required this.value, - }); + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "value": value, - }; - } + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 807bdfd0..632dc3db 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,76 +2,67 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; + /// Identity ID. + final String $id; + /// Identity creation date in ISO 8601 format. + final String $createdAt; + /// Identity update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Identity Provider. + final String provider; + /// ID of the User in the Identity Provider. + final String providerUid; + /// Email of the User in the Identity Provider. + final String providerEmail; + /// Identity Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Identity Provider Refresh Token. + final String providerRefreshToken; - /// Identity creation date in ISO 8601 format. - final String $createdAt; + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); - /// Identity update date in ISO 8601 format. - final String $updatedAt; + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } - /// User ID. - final String userId; - - /// Identity Provider. - final String provider; - - /// ID of the User in the Identity Provider. - final String providerUid; - - /// Email of the User in the Identity Provider. - final String providerEmail; - - /// Identity Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Identity Provider Refresh Token. - final String providerRefreshToken; - - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); - - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index eab513d8..b38c9775 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; + /// Total number of identities documents that matched your query. + final int total; + /// List of identities. + final List identities; - /// List of identities. - final List identities; + IdentityList({ + required this.total, + required this.identities, + }); - IdentityList({ - required this.total, - required this.identities, - }); + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), + ); + } - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from( - map['identities'].map((p) => Identity.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index e2e31bd2..1b4ff7de 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index b6ec6121..6d26c461 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; + /// Language name. + final String name; + /// Language two-character ISO 639-1 codes. + final String code; + /// Language native name. + final String nativeName; - /// Language two-character ISO 639-1 codes. - final String code; + Language({ + required this.name, + required this.code, + required this.nativeName, + }); - /// Language native name. - final String nativeName; + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } - Language({ - required this.name, - required this.code, - required this.nativeName, - }); - - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } - - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index 29f49481..c6977a0e 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; + /// Total number of languages documents that matched your query. + final int total; + /// List of languages. + final List languages; - /// List of languages. - final List languages; + LanguageList({ + required this.total, + required this.languages, + }); - LanguageList({ - required this.total, - required this.languages, - }); + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: - List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 084475bf..0f0fd7f2 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,58 +2,52 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - - /// Country name. This field support localization. - final String country; - - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - - /// Continent name. This field support localization. - final String continent; - - /// True if country is part of the European Union. - final bool eu; - - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + /// Country name. This field support localization. + final String country; + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + /// Continent name. This field support localization. + final String continent; + /// True if country is part of the European Union. + final bool eu; + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index 678e40c4..eebce199 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; + /// Locale name + final String name; - /// Locale name - final String name; + LocaleCode({ + required this.code, + required this.name, + }); - LocaleCode({ - required this.code, - required this.name, - }); + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "name": name, - }; - } + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index c3f4e4be..090b332d 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; + /// Total number of localeCodes documents that matched your query. + final int total; + /// List of localeCodes. + final List localeCodes; - /// List of localeCodes. - final List localeCodes; + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from( - map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 7fb3f364..41cda2ca 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,142 +2,122 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - - /// User ID. - final String userId; - - /// User Email. - final String userEmail; - - /// User Name. - final String userName; - - /// API mode when event triggered. - final String mode; - - /// IP session in use when the session was created. - final String ip; - - /// Log creation date in ISO 8601 format. - final String time; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + /// User ID. + final String userId; + /// User Email. + final String userEmail; + /// User Name. + final String userName; + /// API mode when event triggered. + final String mode; + /// IP session in use when the session was created. + final String ip; + /// Log creation date in ISO 8601 format. + final String time; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index a686897c..9af5b1cd 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; + /// Total number of logs documents that matched your query. + final int total; + /// List of logs. + final List logs; - /// List of logs. - final List logs; + LogList({ + required this.total, + required this.logs, + }); - LogList({ - required this.total, - required this.logs, - }); + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index fb3fb523..283f4ee5 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,94 +2,82 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - - /// Membership creation date in ISO 8601 format. - final String $createdAt; - - /// Membership update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// User name. - final String userName; - - /// User email address. - final String userEmail; - - /// Team ID. - final String teamId; - - /// Team name. - final String teamName; - - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + /// Membership creation date in ISO 8601 format. + final String $createdAt; + /// Membership update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// User name. + final String userName; + /// User email address. + final String userEmail; + /// Team ID. + final String teamId; + /// Team name. + final String teamName; + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index ee65133b..1da7cd60 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; + /// Total number of memberships documents that matched your query. + final int total; + /// List of memberships. + final List memberships; - /// List of memberships. - final List memberships; + MembershipList({ + required this.total, + required this.memberships, + }); - MembershipList({ - required this.total, - required this.memberships, - }); + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), + ); + } - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from( - map['memberships'].map((p) => Membership.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 96bf3c65..043ff286 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token expiration date in ISO 8601 format. + final String expire; - /// Token creation date in ISO 8601 format. - final String $createdAt; + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); - /// User ID. - final String userId; + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } - /// Token expiration date in ISO 8601 format. - final String expire; - - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); - - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index c930a23e..f453e870 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,40 +2,37 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; + /// Can email be used for MFA challenge for this account. + final bool email; + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); - /// Can email be used for MFA challenge for this account. - final bool email; + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; - - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); - - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } - - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 83483901..68402443 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 0573166e..87064007 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; + /// Secret token used for TOTP factor. + final String secret; + /// URI for authenticator apps. + final String uri; - /// URI for authenticator apps. - final String uri; + MfaType({ + required this.secret, + required this.uri, + }); - MfaType({ - required this.secret, - required this.uri, - }); + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } - - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index f810a35b..48e5b84a 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} +} \ No newline at end of file diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 40f7bcd2..24f7260d 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,34 +2,32 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; + /// Phone code. + final String code; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); - /// Country name. - final String countryName; + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); - - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 1ae5a351..55e6108e 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; + /// Total number of phones documents that matched your query. + final int total; + /// List of phones. + final List phones; - /// List of phones. - final List phones; + PhoneList({ + required this.total, + required this.phones, + }); - PhoneList({ - required this.total, - required this.phones, - }); + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3549cff0..3c62f86d 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 1f55d400..10566f44 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,190 +2,162 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - - /// Session creation date in ISO 8601 format. - final String $createdAt; - - /// Session update date in ISO 8601 format. - final String $updatedAt; - - /// User ID. - final String userId; - - /// Session expiration date in ISO 8601 format. - final String expire; - - /// Session Provider. - final String provider; - - /// Session Provider User ID. - final String providerUid; - - /// Session Provider Access Token. - final String providerAccessToken; - - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - - /// Session Provider Refresh Token. - final String providerRefreshToken; - - /// IP in use when the session was created. - final String ip; - - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - - /// Operating system name. - final String osName; - - /// Operating system version. - final String osVersion; - - /// Client type. - final String clientType; - - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - - /// Client name. - final String clientName; - - /// Client version. - final String clientVersion; - - /// Client engine name. - final String clientEngine; - - /// Client engine name. - final String clientEngineVersion; - - /// Device name. - final String deviceName; - - /// Device brand name. - final String deviceBrand; - - /// Device model name. - final String deviceModel; - - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - - /// Country name. - final String countryName; - - /// Returns true if this the current user session. - final bool current; - - /// Returns a list of active session factors. - final List factors; - - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + /// Session creation date in ISO 8601 format. + final String $createdAt; + /// Session update date in ISO 8601 format. + final String $updatedAt; + /// User ID. + final String userId; + /// Session expiration date in ISO 8601 format. + final String expire; + /// Session Provider. + final String provider; + /// Session Provider User ID. + final String providerUid; + /// Session Provider Access Token. + final String providerAccessToken; + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + /// Session Provider Refresh Token. + final String providerRefreshToken; + /// IP in use when the session was created. + final String ip; + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + /// Operating system name. + final String osName; + /// Operating system version. + final String osVersion; + /// Client type. + final String clientType; + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + /// Client name. + final String clientName; + /// Client version. + final String clientVersion; + /// Client engine name. + final String clientEngine; + /// Client engine name. + final String clientEngineVersion; + /// Device name. + final String deviceName; + /// Device brand name. + final String deviceBrand; + /// Device model name. + final String deviceModel; + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + /// Country name. + final String countryName; + /// Returns true if this the current user session. + final bool current; + /// Returns a list of active session factors. + final List factors; + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index e4739c9b..ee4841a2 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,29 +2,27 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; + /// Total number of sessions documents that matched your query. + final int total; + /// List of sessions. + final List sessions; - /// List of sessions. - final List sessions; + SessionList({ + required this.total, + required this.sessions, + }); - SessionList({ - required this.total, - required this.sessions, - }); + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: - List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 0c926297..97bdb018 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,70 +2,62 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - - /// Target ID. - final String targetId; - - /// Target. - final Target target; - - /// Topic ID. - final String userId; - - /// User Name. - final String userName; - - /// Topic ID. - final String topicId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + /// Target ID. + final String targetId; + /// Target. + final Target target; + /// Topic ID. + final String userId; + /// User Name. + final String userName; + /// Topic ID. + final String topicId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 68460126..50134304 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,64 +2,57 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - - /// Target creation time in ISO 8601 format. - final String $createdAt; - - /// Target update date in ISO 8601 format. - final String $updatedAt; - - /// Target Name. - final String name; - - /// User ID. - final String userId; - - /// Provider ID. - final String? providerId; - - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + /// Target creation time in ISO 8601 format. + final String $createdAt; + /// Target update date in ISO 8601 format. + final String $updatedAt; + /// Target Name. + final String name; + /// User ID. + final String userId; + /// Provider ID. + final String? providerId; + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 43df33a8..a55d13c9 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - - /// Team creation date in ISO 8601 format. - final String $createdAt; - - /// Team update date in ISO 8601 format. - final String $updatedAt; - - /// Team name. - final String name; - - /// Total number of team members. - final int total; - - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + /// Team creation date in ISO 8601 format. + final String $createdAt; + /// Team update date in ISO 8601 format. + final String $updatedAt; + /// Team name. + final String name; + /// Total number of team members. + final int total; + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 817e944f..23147a1a 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,28 +2,27 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; + /// Total number of teams documents that matched your query. + final int total; + /// List of teams. + final List teams; - /// List of teams. - final List teams; + TeamList({ + required this.total, + required this.teams, + }); - TeamList({ - required this.total, - required this.teams, - }); + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } - - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 35115467..217006c0 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,52 +2,47 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - - /// Token creation date in ISO 8601 format. - final String $createdAt; - - /// User ID. - final String userId; - - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - - /// Token expiration date in ISO 8601 format. - final String expire; - - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + /// Token creation date in ISO 8601 format. + final String $createdAt; + /// User ID. + final String userId; + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + /// Token expiration date in ISO 8601 format. + final String expire; + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 889005cf..5937ff55 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,130 +2,112 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - - /// User creation date in ISO 8601 format. - final String $createdAt; - - /// User update date in ISO 8601 format. - final String $updatedAt; - - /// User name. - final String name; - - /// Hashed user password. - final String? password; - - /// Password hashing algorithm. - final String? hash; - - /// Password hashing algorithm configuration. - final Map? hashOptions; - - /// User registration date in ISO 8601 format. - final String registration; - - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - - /// Labels for the user. - final List labels; - - /// Password update time in ISO 8601 format. - final String passwordUpdate; - - /// User email address. - final String email; - - /// User phone number in E.164 format. - final String phone; - - /// Email verification status. - final bool emailVerification; - - /// Phone verification status. - final bool phoneVerification; - - /// Multi factor authentication status. - final bool mfa; - - /// User preferences as a key-value object - final Preferences prefs; - - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + /// User creation date in ISO 8601 format. + final String $createdAt; + /// User update date in ISO 8601 format. + final String $updatedAt; + /// User name. + final String name; + /// Hashed user password. + final String? password; + /// Password hashing algorithm. + final String? hash; + /// Password hashing algorithm configuration. + final Map? hashOptions; + /// User registration date in ISO 8601 format. + final String registration; + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + /// Labels for the user. + final List labels; + /// Password update time in ISO 8601 format. + final String passwordUpdate; + /// User email address. + final String email; + /// User phone number in E.164 format. + final String phone; + /// Email verification status. + final bool emailVerification; + /// Phone verification status. + final bool phoneVerification; + /// Multi factor authentication status. + final bool mfa; + /// User preferences as a key-value object + final Preferences prefs; + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index 35f68677..e02d89a5 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 60dc68c7..86bf4045 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,6 +15,7 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { + RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -22,8 +23,7 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && - (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index 372bd0b6..e12b8a4d 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index be87c1bf..fe103280 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if (_creatingSocket || _channels.isEmpty) return; + if(_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index a08eda8e..f09da8da 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,6 +8,7 @@ class RealtimeResponse { required this.type, required this.data, }); + RealtimeResponse copyWith({ String? type, @@ -35,8 +36,7 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => - RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override From 1f3d689550c5a09612e78b35a2197f438516aa80 Mon Sep 17 00:00:00 2001 From: TorstenDittmann Date: Tue, 27 Aug 2024 13:27:37 +0000 Subject: [PATCH 30/30] Commit from GitHub Actions (Format and push) --- lib/appwrite.dart | 2 +- lib/client_browser.dart | 2 +- lib/client_io.dart | 2 +- lib/id.dart | 3 +- lib/query.dart | 45 +- lib/realtime_browser.dart | 2 +- lib/realtime_io.dart | 2 +- lib/role.dart | 106 +- lib/services/account.dart | 2351 +++++++++++----------- lib/services/avatars.dart | 392 ++-- lib/services/databases.dart | 259 ++- lib/services/functions.dart | 158 +- lib/services/graphql.dart | 88 +- lib/services/locale.dart | 248 ++- lib/services/messaging.dart | 93 +- lib/services/storage.dart | 442 ++-- lib/services/teams.dart | 647 +++--- lib/src/client.dart | 9 +- lib/src/client_base.dart | 4 +- lib/src/client_browser.dart | 14 +- lib/src/client_io.dart | 74 +- lib/src/client_mixin.dart | 33 +- lib/src/enums/authentication_factor.dart | 18 +- lib/src/enums/authenticator_type.dart | 12 +- lib/src/enums/browser.dart | 38 +- lib/src/enums/credit_card.dart | 42 +- lib/src/enums/execution_method.dart | 22 +- lib/src/enums/flag.dart | 400 ++-- lib/src/enums/image_format.dart | 20 +- lib/src/enums/image_gravity.dart | 28 +- lib/src/enums/o_auth_provider.dart | 88 +- lib/src/exception.dart | 2 +- lib/src/models/algo_argon2.dart | 63 +- lib/src/models/algo_bcrypt.dart | 30 +- lib/src/models/algo_md5.dart | 30 +- lib/src/models/algo_phpass.dart | 30 +- lib/src/models/algo_scrypt.dart | 80 +- lib/src/models/algo_scrypt_modified.dart | 63 +- lib/src/models/algo_sha.dart | 30 +- lib/src/models/continent.dart | 41 +- lib/src/models/continent_list.dart | 42 +- lib/src/models/country.dart | 41 +- lib/src/models/country_list.dart | 42 +- lib/src/models/currency.dart | 102 +- lib/src/models/currency_list.dart | 42 +- lib/src/models/document.dart | 103 +- lib/src/models/document_list.dart | 46 +- lib/src/models/execution.dart | 214 +- lib/src/models/execution_list.dart | 42 +- lib/src/models/file.dart | 140 +- lib/src/models/file_list.dart | 41 +- lib/src/models/headers.dart | 41 +- lib/src/models/identity.dart | 129 +- lib/src/models/identity_list.dart | 42 +- lib/src/models/jwt.dart | 30 +- lib/src/models/language.dart | 52 +- lib/src/models/language_list.dart | 42 +- lib/src/models/locale.dart | 102 +- lib/src/models/locale_code.dart | 41 +- lib/src/models/locale_code_list.dart | 42 +- lib/src/models/log.dart | 256 +-- lib/src/models/log_list.dart | 41 +- lib/src/models/membership.dart | 168 +- lib/src/models/membership_list.dart | 42 +- lib/src/models/mfa_challenge.dart | 63 +- lib/src/models/mfa_factors.dart | 63 +- lib/src/models/mfa_recovery_codes.dart | 30 +- lib/src/models/mfa_type.dart | 41 +- lib/src/models/model.dart | 2 +- lib/src/models/phone.dart | 52 +- lib/src/models/phone_list.dart | 41 +- lib/src/models/preferences.dart | 30 +- lib/src/models/session.dart | 344 ++-- lib/src/models/session_list.dart | 42 +- lib/src/models/subscriber.dart | 124 +- lib/src/models/target.dart | 113 +- lib/src/models/team.dart | 91 +- lib/src/models/team_list.dart | 41 +- lib/src/models/token.dart | 91 +- lib/src/models/user.dart | 234 ++- lib/src/realtime.dart | 6 +- lib/src/realtime_io.dart | 4 +- lib/src/realtime_message.dart | 2 +- lib/src/realtime_mixin.dart | 2 +- lib/src/realtime_response.dart | 10 +- 85 files changed, 4842 insertions(+), 4480 deletions(-) diff --git a/lib/appwrite.dart b/lib/appwrite.dart index d0c2331e..c89bac24 100644 --- a/lib/appwrite.dart +++ b/lib/appwrite.dart @@ -1,6 +1,6 @@ /// Appwrite Flutter SDK /// -/// This SDK is compatible with Appwrite server version 1.6.x. +/// This SDK is compatible with Appwrite server version 1.6.x. /// For older versions, please check /// [previous releases](https://github.com/appwrite/sdk-for-flutter/releases). library appwrite; diff --git a/lib/client_browser.dart b/lib/client_browser.dart index 09f110ea..b9805a3a 100644 --- a/lib/client_browser.dart +++ b/lib/client_browser.dart @@ -1 +1 @@ -export 'src/client_browser.dart'; \ No newline at end of file +export 'src/client_browser.dart'; diff --git a/lib/client_io.dart b/lib/client_io.dart index 4d85cbfa..42a0c0b6 100644 --- a/lib/client_io.dart +++ b/lib/client_io.dart @@ -1 +1 @@ -export 'src/client_io.dart'; \ No newline at end of file +export 'src/client_io.dart'; diff --git a/lib/id.dart b/lib/id.dart index c1d473ce..1443ada7 100644 --- a/lib/id.dart +++ b/lib/id.dart @@ -10,8 +10,7 @@ class ID { final now = DateTime.now(); final sec = (now.millisecondsSinceEpoch / 1000).floor(); final usec = now.microsecondsSinceEpoch - (sec * 1000000); - return sec.toRadixString(16) + - usec.toRadixString(16).padLeft(5, '0'); + return sec.toRadixString(16) + usec.toRadixString(16).padLeft(5, '0'); } // Generate a unique ID with padding to have a longer ID diff --git a/lib/query.dart b/lib/query.dart index 82d0c544..e407f7fe 100644 --- a/lib/query.dart +++ b/lib/query.dart @@ -1,6 +1,5 @@ part of 'appwrite.dart'; - /// Helper class to generate query strings. class Query { final String method; @@ -14,11 +13,11 @@ class Query { 'method': method, }; - if(attribute != null) { + if (attribute != null) { map['attribute'] = attribute; } - - if(values != null) { + + if (values != null) { map['values'] = values is List ? values : [values]; } @@ -29,7 +28,7 @@ class Query { String toString() => jsonEncode(toJson()); /// Filter resources where [attribute] is equal to [value]. - /// + /// /// [value] can be a single value or a list. If a list is used /// the query will return resources where [attribute] is equal /// to any of the values in the list. @@ -61,10 +60,12 @@ class Query { Query._('search', attribute, value).toString(); /// Filter resources where [attribute] is null. - static String isNull(String attribute) => Query._('isNull', attribute).toString(); + static String isNull(String attribute) => + Query._('isNull', attribute).toString(); /// Filter resources where [attribute] is not null. - static String isNotNull(String attribute) => Query._('isNotNull', attribute).toString(); + static String isNotNull(String attribute) => + Query._('isNotNull', attribute).toString(); /// Filter resources where [attribute] is between [start] and [end] (inclusive). static String between(String attribute, dynamic start, dynamic end) => @@ -84,40 +85,46 @@ class Query { Query._('contains', attribute, value).toString(); static String or(List queries) => - Query._('or', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('or', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); static String and(List queries) => - Query._('and', null, queries.map((query) => jsonDecode(query)).toList()).toString(); + Query._('and', null, queries.map((query) => jsonDecode(query)).toList()) + .toString(); /// Specify which attributes should be returned by the API call. static String select(List attributes) => Query._('select', null, attributes).toString(); /// Sort results by [attribute] ascending. - static String orderAsc(String attribute) => Query._('orderAsc', attribute).toString(); + static String orderAsc(String attribute) => + Query._('orderAsc', attribute).toString(); /// Sort results by [attribute] descending. - static String orderDesc(String attribute) => Query._('orderDesc', attribute).toString(); + static String orderDesc(String attribute) => + Query._('orderDesc', attribute).toString(); /// Return results before [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorBefore(String id) => Query._('cursorBefore', null, id).toString(); + static String cursorBefore(String id) => + Query._('cursorBefore', null, id).toString(); /// Return results after [id]. - /// + /// /// Refer to the [Cursor Based Pagination](https://appwrite.io/docs/pagination#cursor-pagination) /// docs for more information. - static String cursorAfter(String id) => Query._('cursorAfter', null, id).toString(); + static String cursorAfter(String id) => + Query._('cursorAfter', null, id).toString(); /// Return only [limit] results. static String limit(int limit) => Query._('limit', null, limit).toString(); /// Return results from [offset]. - /// + /// /// Refer to the [Offset Pagination](https://appwrite.io/docs/pagination#offset-pagination) /// docs for more information. - static String offset(int offset) => Query._('offset', null, offset).toString(); - -} \ No newline at end of file + static String offset(int offset) => + Query._('offset', null, offset).toString(); +} diff --git a/lib/realtime_browser.dart b/lib/realtime_browser.dart index 5aa5f420..05e8456e 100644 --- a/lib/realtime_browser.dart +++ b/lib/realtime_browser.dart @@ -1 +1 @@ -export 'src/realtime_browser.dart'; \ No newline at end of file +export 'src/realtime_browser.dart'; diff --git a/lib/realtime_io.dart b/lib/realtime_io.dart index 5f557007..750cbe20 100644 --- a/lib/realtime_io.dart +++ b/lib/realtime_io.dart @@ -1 +1 @@ -export 'src/realtime_io.dart'; \ No newline at end of file +export 'src/realtime_io.dart'; diff --git a/lib/role.dart b/lib/role.dart index 103f120c..9eae13b6 100644 --- a/lib/role.dart +++ b/lib/role.dart @@ -2,65 +2,65 @@ part of 'appwrite.dart'; /// Helper class to generate role strings for [Permission]. class Role { - Role._(); - - /// Grants access to anyone. - /// - /// This includes authenticated and unauthenticated users. - static String any() { - return 'any'; - } + Role._(); - /// Grants access to a specific user by user ID. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String user(String id, [String status = '']) { - if(status.isEmpty) { - return 'user:$id'; - } - return 'user:$id/$status'; - } + /// Grants access to anyone. + /// + /// This includes authenticated and unauthenticated users. + static String any() { + return 'any'; + } - /// Grants access to any authenticated or anonymous user. - /// - /// You can optionally pass verified or unverified for - /// [status] to target specific types of users. - static String users([String status = '']) { - if(status.isEmpty) { - return 'users'; - } - return 'users/$status'; + /// Grants access to a specific user by user ID. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String user(String id, [String status = '']) { + if (status.isEmpty) { + return 'user:$id'; } + return 'user:$id/$status'; + } - /// Grants access to any guest user without a session. - /// - /// Authenticated users don't have access to this role. - static String guests() { - return 'guests'; + /// Grants access to any authenticated or anonymous user. + /// + /// You can optionally pass verified or unverified for + /// [status] to target specific types of users. + static String users([String status = '']) { + if (status.isEmpty) { + return 'users'; } + return 'users/$status'; + } - /// Grants access to a team by team ID. - /// - /// You can optionally pass a role for [role] to target - /// team members with the specified role. - static String team(String id, [String role = '']) { - if(role.isEmpty) { - return 'team:$id'; - } - return 'team:$id/$role'; - } + /// Grants access to any guest user without a session. + /// + /// Authenticated users don't have access to this role. + static String guests() { + return 'guests'; + } - /// Grants access to a specific member of a team. - /// - /// When the member is removed from the team, they will - /// no longer have access. - static String member(String id) { - return 'member:$id'; + /// Grants access to a team by team ID. + /// + /// You can optionally pass a role for [role] to target + /// team members with the specified role. + static String team(String id, [String role = '']) { + if (role.isEmpty) { + return 'team:$id'; } + return 'team:$id/$role'; + } - /// Grants access to a user with the specified label. - static String label(String name) { - return 'label:$name'; - } -} \ No newline at end of file + /// Grants access to a specific member of a team. + /// + /// When the member is removed from the team, they will + /// no longer have access. + static String member(String id) { + return 'member:$id'; + } + + /// Grants access to a user with the specified label. + static String label(String name) { + return 'label:$name'; + } +} diff --git a/lib/services/account.dart b/lib/services/account.dart index 92803ae6..a94a37d2 100644 --- a/lib/services/account.dart +++ b/lib/services/account.dart @@ -2,1163 +2,1194 @@ part of '../appwrite.dart'; /// The Account service allows you to authenticate and manage a user account. class Account extends Service { - /// Initializes a [Account] service - Account(super.client); - - /// Get account - /// - /// Get the currently logged in user. - Future get() async { - const String apiPath = '/account'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create account - /// - /// Use this endpoint to allow a new user to register a new account in your - /// project. After the user registration completes successfully, you can use - /// the - /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - /// route to start verifying the user email address. To allow the new user to - /// login to their new account, you need to create a new [account - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - Future create({required String userId, required String email, required String password, String? name}) async { - const String apiPath = '/account'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'password': password, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update email - /// - /// Update currently logged in user account email address. After changing user - /// address, the user confirmation status will get reset. A new confirmation - /// email is not sent automatically however you can use the send confirmation - /// email endpoint again to send the confirmation email. For security measures, - /// user password is required to complete this request. - /// This endpoint can also be used to convert an anonymous account to a normal - /// one, by passing an email address and a new password. - /// - Future updateEmail({required String email, required String password}) async { - const String apiPath = '/account/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// List Identities - /// - /// Get the list of identities for the currently logged in user. - Future listIdentities({List? queries}) async { - const String apiPath = '/account/identities'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.IdentityList.fromMap(res.data); - - } - - /// Delete identity - /// - /// Delete an identity by its unique ID. - Future deleteIdentity({required String identityId}) async { - final String apiPath = '/account/identities/{identityId}'.replaceAll('{identityId}', identityId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create JWT - /// - /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT - /// to authenticate on behalf of the current user when working with the - /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - /// from its creation and will be invalid if the user will logout in that time - /// frame. - Future createJWT() async { - const String apiPath = '/account/jwts'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Jwt.fromMap(res.data); - - } - - /// List logs - /// - /// Get the list of latest security activity logs for the currently logged in - /// user. Each log returns user IP address, location and date and time of log. - Future listLogs({List? queries}) async { - const String apiPath = '/account/logs'; - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LogList.fromMap(res.data); - - } - - /// Update MFA - /// - /// Enable or disable MFA on an account. - Future updateMFA({required bool mfa}) async { - const String apiPath = '/account/mfa'; - - final Map apiParams = { - 'mfa': mfa, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create Authenticator - /// - /// Add an authenticator app to be used as an MFA factor. Verify the - /// authenticator using the [verify - /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - /// method. - Future createMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaType.fromMap(res.data); - - } - - /// Verify Authenticator - /// - /// Verify an authenticator app after adding it using the [add - /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - /// method. - Future updateMfaAuthenticator({required enums.AuthenticatorType type, required String otp}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Delete Authenticator - /// - /// Delete an authenticator for a user by ID. - Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { - final String apiPath = '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create MFA Challenge - /// - /// Begin the process of MFA verification after sign-in. Finish the flow with - /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - /// method. - Future createMfaChallenge({required enums.AuthenticationFactor factor}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'factor': factor.value, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaChallenge.fromMap(res.data); - - } - - /// Create MFA Challenge (confirmation) - /// - /// Complete the MFA challenge by providing the one-time password. Finish the - /// process of MFA verification by providing the one-time password. To begin - /// the flow, use - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future updateMfaChallenge({required String challengeId, required String otp}) async { - const String apiPath = '/account/mfa/challenge'; - - final Map apiParams = { - 'challengeId': challengeId, - 'otp': otp, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List Factors - /// - /// List the factors available on the account to be used as a MFA challange. - Future listMfaFactors() async { - const String apiPath = '/account/mfa/factors'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaFactors.fromMap(res.data); - - } - - /// Get MFA Recovery Codes - /// - /// Get recovery codes that can be used as backup for MFA flow. Before getting - /// codes, they must be generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to read recovery codes. - Future getMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Create MFA Recovery Codes - /// - /// Generate recovery codes as backup for MFA flow. It's recommended to - /// generate and show then immediately after user successfully adds their - /// authehticator. Recovery codes can be used as a MFA verification type in - /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - /// method. - Future createMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Regenerate MFA Recovery Codes - /// - /// Regenerate recovery codes that can be used as backup for MFA flow. Before - /// regenerating codes, they must be first generated using - /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - /// method. An OTP challenge is required to regenreate recovery codes. - Future updateMfaRecoveryCodes() async { - const String apiPath = '/account/mfa/recovery-codes'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MfaRecoveryCodes.fromMap(res.data); - - } - - /// Update name - /// - /// Update currently logged in user account name. - Future updateName({required String name}) async { - const String apiPath = '/account/name'; - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update password - /// - /// Update currently logged in user password. For validation, user is required - /// to pass in the new password, and the old password. For users created with - /// OAuth, Team Invites and Magic URL, oldPassword is optional. - Future updatePassword({required String password, String? oldPassword}) async { - const String apiPath = '/account/password'; - - final Map apiParams = { - 'password': password, - 'oldPassword': oldPassword, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Update phone - /// - /// Update the currently logged in user's phone number. After updating the - /// phone number, the phone verification status will be reset. A confirmation - /// SMS is not sent automatically, however you can use the [POST - /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - /// endpoint to send a confirmation SMS. - Future updatePhone({required String phone, required String password}) async { - const String apiPath = '/account/phone'; - - final Map apiParams = { - 'phone': phone, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Get account preferences - /// - /// Get the preferences as a key-value object for the currently logged in user. - Future getPrefs() async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update currently logged in user account preferences. The object you pass is - /// stored as is, and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws error if exceeded. - Future updatePrefs({required Map prefs}) async { - const String apiPath = '/account/prefs'; - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create password recovery - /// - /// Sends the user an email with a temporary secret key for password reset. - /// When the user clicks the confirmation link he is redirected back to your - /// app password reset URL with the secret key and email address values - /// attached to the URL query string. Use the query string params to submit a - /// request to the [PUT - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - /// endpoint to complete the process. The verification link sent to the user's - /// email address is valid for 1 hour. - Future createRecovery({required String email, required String url}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'email': email, - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create password recovery (confirmation) - /// - /// Use this endpoint to complete the user account password reset. Both the - /// **userId** and **secret** arguments will be passed as query parameters to - /// the redirect URL you have provided when sending your request to the [POST - /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - /// endpoint. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - Future updateRecovery({required String userId, required String secret, required String password}) async { - const String apiPath = '/account/recovery'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// List sessions - /// - /// Get the list of active sessions across different devices for the currently - /// logged in user. - Future listSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.SessionList.fromMap(res.data); - - } - - /// Delete sessions - /// - /// Delete all sessions from the user account and remove any sessions cookies - /// from the end client. - Future deleteSessions() async { - const String apiPath = '/account/sessions'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create anonymous session - /// - /// Use this endpoint to allow a new user to register an anonymous account in - /// your project. This route will also create a new session for the user. To - /// allow the new user to convert an anonymous account to a normal account, you - /// need to update its [email and - /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - /// or create an [OAuth2 - /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). - Future createAnonymousSession() async { - const String apiPath = '/account/sessions/anonymous'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create email password session - /// - /// Allow the user to login into their account by providing a valid email and - /// password combination. This route will create a new session for the user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailPasswordSession({required String email, required String password}) async { - const String apiPath = '/account/sessions/email'; - - final Map apiParams = { - 'email': email, - 'password': password, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update magic URL session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updateMagicURLSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create OAuth2 session - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If there is already an active session, the new session will be attached to - /// the logged-in account. If there are no active sessions, the server will - /// attempt to look for a user with the same email address as the email - /// received from the OAuth2 provider and attach the new session to the - /// existing user. If no matching user is found - the server will create a new - /// user. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createOAuth2Session({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/sessions/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Update phone session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future updatePhoneSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Create session - /// - /// Use this endpoint to create a session from token. Provide the **userId** - /// and **secret** parameters from the successful response of authentication - /// flows initiated by token creation. For example, magic URL and phone login. - Future createSession({required String userId, required String secret}) async { - const String apiPath = '/account/sessions/token'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Get session - /// - /// Use this endpoint to get a logged in user's session using a Session ID. - /// Inputting 'current' will return the current session being used. - Future getSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Update session - /// - /// Use this endpoint to extend a session's length. Extending a session is - /// useful when session expiry is short. If the session was created using an - /// OAuth provider, this endpoint refreshes the access token from the provider. - Future updateSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Session.fromMap(res.data); - - } - - /// Delete session - /// - /// Logout the user. Use 'current' as the session ID to logout on this device, - /// use a session ID to logout on another device. If you're looking to logout - /// the user on all devices, use [Delete - /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - /// instead. - Future deleteSession({required String sessionId}) async { - final String apiPath = '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update status - /// - /// Block the currently logged in user account. Behind the scene, the user - /// record is not deleted but permanently blocked from any access. To - /// completely delete a user, use the Users API instead. - Future updateStatus() async { - const String apiPath = '/account/status'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.User.fromMap(res.data); - - } - - /// Create push target - /// - Future createPushTarget({required String targetId, required String identifier, String? providerId}) async { - const String apiPath = '/account/targets/push'; - - final Map apiParams = { - 'targetId': targetId, - 'identifier': identifier, - 'providerId': providerId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Update push target - /// - Future updatePushTarget({required String targetId, required String identifier}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - 'identifier': identifier, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Target.fromMap(res.data); - - } - - /// Delete push target - /// - Future deletePushTarget({required String targetId}) async { - final String apiPath = '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Create email token (OTP) - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's email - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createEmailToken({required String userId, required String email, bool? phrase}) async { - const String apiPath = '/account/tokens/email'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create magic URL token - /// - /// Sends the user an email with a secret key for creating a session. If the - /// provided user ID has not been registered, a new user will be created. When - /// the user clicks the link in the email, the user is redirected back to the - /// URL you provided with the secret key and userId values attached to the URL - /// query string. Use the query string parameters to submit a request to the - /// [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The link sent to the user's email - /// address is valid for 1 hour. If you are on a mobile device you can leave - /// the URL parameter empty, so that the login completion will be handled by - /// your Appwrite instance by default. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - /// - Future createMagicURLToken({required String userId, required String email, String? url, bool? phrase}) async { - const String apiPath = '/account/tokens/magic-url'; - - final Map apiParams = { - 'userId': userId, - 'email': email, - 'url': url, - 'phrase': phrase, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create OAuth2 token - /// - /// Allow the user to login to their account using the OAuth2 provider of their - /// choice. Each OAuth2 provider should be enabled from the Appwrite console - /// first. Use the success and failure arguments to provide a redirect URL's - /// back to your app when login is completed. - /// - /// If authentication succeeds, `userId` and `secret` of a token will be - /// appended to the success URL as query parameters. These can be used to - /// create a new session using the [Create - /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createOAuth2Token({required enums.OAuthProvider provider, String? success, String? failure, List? scopes}) async { - final String apiPath = '/account/tokens/oauth2/{provider}'.replaceAll('{provider}', provider.value); - - final Map params = { - - 'success': success, - 'failure': failure, - 'scopes': scopes, - - 'project': client.config['project'], - }; - - final List query = []; - - params.forEach((key, value) { - if (value is List) { - for (var item in value) { - query.add(Uri.encodeComponent(key + '[]') + '=' + Uri.encodeComponent(item)); - } - } else if(value != null) { - query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); - } - }); - - Uri endpoint = Uri.parse(client.endPoint); - Uri url = Uri(scheme: endpoint.scheme, - host: endpoint.host, - port: endpoint.port, - path: endpoint.path + apiPath, - query: query.join('&') - ); - - return client.webAuth(url, callbackUrlScheme: success); - } - - /// Create phone token - /// - /// Sends the user an SMS with a secret key for creating a session. If the - /// provided user ID has not be registered, a new user will be created. Use the - /// returned user ID and secret and submit a request to the [POST - /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - /// endpoint to complete the login process. The secret sent to the user's phone - /// is valid for 15 minutes. - /// - /// A user is limited to 10 active sessions at a time by default. [Learn more - /// about session - /// limits](https://appwrite.io/docs/authentication-security#limits). - Future createPhoneToken({required String userId, required String phone}) async { - const String apiPath = '/account/tokens/phone'; - - final Map apiParams = { - 'userId': userId, - 'phone': phone, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification - /// - /// Use this endpoint to send a verification message to your user email address - /// to confirm they are the valid owners of that address. Both the **userId** - /// and **secret** arguments will be passed as query parameters to the URL you - /// have provided to be attached to the verification email. The provided URL - /// should redirect the user back to your app and allow you to complete the - /// verification process by verifying both the **userId** and **secret** - /// parameters. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - /// The verification link sent to the user's email address is valid for 7 days. - /// - /// Please note that in order to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - /// the only valid redirect URLs are the ones from domains you have set when - /// adding your platforms in the console interface. - /// - Future createVerification({required String url}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'url': url, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create email verification (confirmation) - /// - /// Use this endpoint to complete the user email verification process. Use both - /// the **userId** and **secret** parameters that were attached to your app URL - /// to verify the user email ownership. If confirmed this route will return a - /// 200 status code. - Future updateVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Create phone verification - /// - /// Use this endpoint to send a verification SMS to the currently logged in - /// user. This endpoint is meant for use after updating a user's phone number - /// using the - /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - /// endpoint. Learn more about how to [complete the verification - /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - /// The verification code sent to the user's phone number is valid for 15 - /// minutes. - Future createPhoneVerification() async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } - - /// Update phone verification (confirmation) - /// - /// Use this endpoint to complete the user phone verification process. Use the - /// **userId** and **secret** that were sent to your user's phone number to - /// verify the user email ownership. If confirmed this route will return a 200 - /// status code. - Future updatePhoneVerification({required String userId, required String secret}) async { - const String apiPath = '/account/verification/phone'; - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Token.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Account] service + Account(super.client); + + /// Get account + /// + /// Get the currently logged in user. + Future get() async { + const String apiPath = '/account'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create account + /// + /// Use this endpoint to allow a new user to register a new account in your + /// project. After the user registration completes successfully, you can use + /// the + /// [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) + /// route to start verifying the user email address. To allow the new user to + /// login to their new account, you need to create a new [account + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + Future create( + {required String userId, + required String email, + required String password, + String? name}) async { + const String apiPath = '/account'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'password': password, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update email + /// + /// Update currently logged in user account email address. After changing user + /// address, the user confirmation status will get reset. A new confirmation + /// email is not sent automatically however you can use the send confirmation + /// email endpoint again to send the confirmation email. For security measures, + /// user password is required to complete this request. + /// This endpoint can also be used to convert an anonymous account to a normal + /// one, by passing an email address and a new password. + /// + Future updateEmail( + {required String email, required String password}) async { + const String apiPath = '/account/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// List Identities + /// + /// Get the list of identities for the currently logged in user. + Future listIdentities({List? queries}) async { + const String apiPath = '/account/identities'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.IdentityList.fromMap(res.data); + } + + /// Delete identity + /// + /// Delete an identity by its unique ID. + Future deleteIdentity({required String identityId}) async { + final String apiPath = '/account/identities/{identityId}' + .replaceAll('{identityId}', identityId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create JWT + /// + /// Use this endpoint to create a JSON Web Token. You can use the resulting JWT + /// to authenticate on behalf of the current user when working with the + /// Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes + /// from its creation and will be invalid if the user will logout in that time + /// frame. + Future createJWT() async { + const String apiPath = '/account/jwts'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Jwt.fromMap(res.data); + } + + /// List logs + /// + /// Get the list of latest security activity logs for the currently logged in + /// user. Each log returns user IP address, location and date and time of log. + Future listLogs({List? queries}) async { + const String apiPath = '/account/logs'; + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.LogList.fromMap(res.data); + } + + /// Update MFA + /// + /// Enable or disable MFA on an account. + Future updateMFA({required bool mfa}) async { + const String apiPath = '/account/mfa'; + + final Map apiParams = { + 'mfa': mfa, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create Authenticator + /// + /// Add an authenticator app to be used as an MFA factor. Verify the + /// authenticator using the [verify + /// authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) + /// method. + Future createMfaAuthenticator( + {required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaType.fromMap(res.data); + } + + /// Verify Authenticator + /// + /// Verify an authenticator app after adding it using the [add + /// authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) + /// method. + Future updateMfaAuthenticator( + {required enums.AuthenticatorType type, required String otp}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = { + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Delete Authenticator + /// + /// Delete an authenticator for a user by ID. + Future deleteMfaAuthenticator({required enums.AuthenticatorType type}) async { + final String apiPath = + '/account/mfa/authenticators/{type}'.replaceAll('{type}', type.value); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create MFA Challenge + /// + /// Begin the process of MFA verification after sign-in. Finish the flow with + /// [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) + /// method. + Future createMfaChallenge( + {required enums.AuthenticationFactor factor}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'factor': factor.value, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaChallenge.fromMap(res.data); + } + + /// Create MFA Challenge (confirmation) + /// + /// Complete the MFA challenge by providing the one-time password. Finish the + /// process of MFA verification by providing the one-time password. To begin + /// the flow, use + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future updateMfaChallenge( + {required String challengeId, required String otp}) async { + const String apiPath = '/account/mfa/challenge'; + + final Map apiParams = { + 'challengeId': challengeId, + 'otp': otp, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List Factors + /// + /// List the factors available on the account to be used as a MFA challange. + Future listMfaFactors() async { + const String apiPath = '/account/mfa/factors'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaFactors.fromMap(res.data); + } + + /// Get MFA Recovery Codes + /// + /// Get recovery codes that can be used as backup for MFA flow. Before getting + /// codes, they must be generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to read recovery codes. + Future getMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Create MFA Recovery Codes + /// + /// Generate recovery codes as backup for MFA flow. It's recommended to + /// generate and show then immediately after user successfully adds their + /// authehticator. Recovery codes can be used as a MFA verification type in + /// [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) + /// method. + Future createMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Regenerate MFA Recovery Codes + /// + /// Regenerate recovery codes that can be used as backup for MFA flow. Before + /// regenerating codes, they must be first generated using + /// [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) + /// method. An OTP challenge is required to regenreate recovery codes. + Future updateMfaRecoveryCodes() async { + const String apiPath = '/account/mfa/recovery-codes'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MfaRecoveryCodes.fromMap(res.data); + } + + /// Update name + /// + /// Update currently logged in user account name. + Future updateName({required String name}) async { + const String apiPath = '/account/name'; + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update password + /// + /// Update currently logged in user password. For validation, user is required + /// to pass in the new password, and the old password. For users created with + /// OAuth, Team Invites and Magic URL, oldPassword is optional. + Future updatePassword( + {required String password, String? oldPassword}) async { + const String apiPath = '/account/password'; + + final Map apiParams = { + 'password': password, + 'oldPassword': oldPassword, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Update phone + /// + /// Update the currently logged in user's phone number. After updating the + /// phone number, the phone verification status will be reset. A confirmation + /// SMS is not sent automatically, however you can use the [POST + /// /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) + /// endpoint to send a confirmation SMS. + Future updatePhone( + {required String phone, required String password}) async { + const String apiPath = '/account/phone'; + + final Map apiParams = { + 'phone': phone, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Get account preferences + /// + /// Get the preferences as a key-value object for the currently logged in user. + Future getPrefs() async { + const String apiPath = '/account/prefs'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update currently logged in user account preferences. The object you pass is + /// stored as is, and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws error if exceeded. + Future updatePrefs({required Map prefs}) async { + const String apiPath = '/account/prefs'; + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create password recovery + /// + /// Sends the user an email with a temporary secret key for password reset. + /// When the user clicks the confirmation link he is redirected back to your + /// app password reset URL with the secret key and email address values + /// attached to the URL query string. Use the query string params to submit a + /// request to the [PUT + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) + /// endpoint to complete the process. The verification link sent to the user's + /// email address is valid for 1 hour. + Future createRecovery( + {required String email, required String url}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'email': email, + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create password recovery (confirmation) + /// + /// Use this endpoint to complete the user account password reset. Both the + /// **userId** and **secret** arguments will be passed as query parameters to + /// the redirect URL you have provided when sending your request to the [POST + /// /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) + /// endpoint. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + Future updateRecovery( + {required String userId, + required String secret, + required String password}) async { + const String apiPath = '/account/recovery'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// List sessions + /// + /// Get the list of active sessions across different devices for the currently + /// logged in user. + Future listSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.SessionList.fromMap(res.data); + } + + /// Delete sessions + /// + /// Delete all sessions from the user account and remove any sessions cookies + /// from the end client. + Future deleteSessions() async { + const String apiPath = '/account/sessions'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create anonymous session + /// + /// Use this endpoint to allow a new user to register an anonymous account in + /// your project. This route will also create a new session for the user. To + /// allow the new user to convert an anonymous account to a normal account, you + /// need to update its [email and + /// password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) + /// or create an [OAuth2 + /// session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + Future createAnonymousSession() async { + const String apiPath = '/account/sessions/anonymous'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create email password session + /// + /// Allow the user to login into their account by providing a valid email and + /// password combination. This route will create a new session for the user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailPasswordSession( + {required String email, required String password}) async { + const String apiPath = '/account/sessions/email'; + + final Map apiParams = { + 'email': email, + 'password': password, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update magic URL session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updateMagicURLSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create OAuth2 session + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If there is already an active session, the new session will be attached to + /// the logged-in account. If there are no active sessions, the server will + /// attempt to look for a user with the same email address as the email + /// received from the OAuth2 provider and attach the new session to the + /// existing user. If no matching user is found - the server will create a new + /// user. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createOAuth2Session( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/sessions/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Update phone session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future updatePhoneSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Create session + /// + /// Use this endpoint to create a session from token. Provide the **userId** + /// and **secret** parameters from the successful response of authentication + /// flows initiated by token creation. For example, magic URL and phone login. + Future createSession( + {required String userId, required String secret}) async { + const String apiPath = '/account/sessions/token'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Get session + /// + /// Use this endpoint to get a logged in user's session using a Session ID. + /// Inputting 'current' will return the current session being used. + Future getSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Update session + /// + /// Use this endpoint to extend a session's length. Extending a session is + /// useful when session expiry is short. If the session was created using an + /// OAuth provider, this endpoint refreshes the access token from the provider. + Future updateSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Session.fromMap(res.data); + } + + /// Delete session + /// + /// Logout the user. Use 'current' as the session ID to logout on this device, + /// use a session ID to logout on another device. If you're looking to logout + /// the user on all devices, use [Delete + /// Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) + /// instead. + Future deleteSession({required String sessionId}) async { + final String apiPath = + '/account/sessions/{sessionId}'.replaceAll('{sessionId}', sessionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update status + /// + /// Block the currently logged in user account. Behind the scene, the user + /// record is not deleted but permanently blocked from any access. To + /// completely delete a user, use the Users API instead. + Future updateStatus() async { + const String apiPath = '/account/status'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.User.fromMap(res.data); + } + + /// Create push target + /// + Future createPushTarget( + {required String targetId, + required String identifier, + String? providerId}) async { + const String apiPath = '/account/targets/push'; + + final Map apiParams = { + 'targetId': targetId, + 'identifier': identifier, + 'providerId': providerId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Update push target + /// + Future updatePushTarget( + {required String targetId, required String identifier}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = { + 'identifier': identifier, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Target.fromMap(res.data); + } + + /// Delete push target + /// + Future deletePushTarget({required String targetId}) async { + final String apiPath = + '/account/targets/{targetId}/push'.replaceAll('{targetId}', targetId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Create email token (OTP) + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's email + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createEmailToken( + {required String userId, required String email, bool? phrase}) async { + const String apiPath = '/account/tokens/email'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create magic URL token + /// + /// Sends the user an email with a secret key for creating a session. If the + /// provided user ID has not been registered, a new user will be created. When + /// the user clicks the link in the email, the user is redirected back to the + /// URL you provided with the secret key and userId values attached to the URL + /// query string. Use the query string parameters to submit a request to the + /// [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The link sent to the user's email + /// address is valid for 1 hour. If you are on a mobile device you can leave + /// the URL parameter empty, so that the login completion will be handled by + /// your Appwrite instance by default. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + /// + Future createMagicURLToken( + {required String userId, + required String email, + String? url, + bool? phrase}) async { + const String apiPath = '/account/tokens/magic-url'; + + final Map apiParams = { + 'userId': userId, + 'email': email, + 'url': url, + 'phrase': phrase, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create OAuth2 token + /// + /// Allow the user to login to their account using the OAuth2 provider of their + /// choice. Each OAuth2 provider should be enabled from the Appwrite console + /// first. Use the success and failure arguments to provide a redirect URL's + /// back to your app when login is completed. + /// + /// If authentication succeeds, `userId` and `secret` of a token will be + /// appended to the success URL as query parameters. These can be used to + /// create a new session using the [Create + /// session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createOAuth2Token( + {required enums.OAuthProvider provider, + String? success, + String? failure, + List? scopes}) async { + final String apiPath = '/account/tokens/oauth2/{provider}' + .replaceAll('{provider}', provider.value); + + final Map params = { + 'success': success, + 'failure': failure, + 'scopes': scopes, + 'project': client.config['project'], + }; + + final List query = []; + + params.forEach((key, value) { + if (value is List) { + for (var item in value) { + query.add(Uri.encodeComponent(key + '[]') + + '=' + + Uri.encodeComponent(item)); + } + } else if (value != null) { + query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value)); + } + }); + + Uri endpoint = Uri.parse(client.endPoint); + Uri url = Uri( + scheme: endpoint.scheme, + host: endpoint.host, + port: endpoint.port, + path: endpoint.path + apiPath, + query: query.join('&')); + + return client.webAuth(url, callbackUrlScheme: success); + } + + /// Create phone token + /// + /// Sends the user an SMS with a secret key for creating a session. If the + /// provided user ID has not be registered, a new user will be created. Use the + /// returned user ID and secret and submit a request to the [POST + /// /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) + /// endpoint to complete the login process. The secret sent to the user's phone + /// is valid for 15 minutes. + /// + /// A user is limited to 10 active sessions at a time by default. [Learn more + /// about session + /// limits](https://appwrite.io/docs/authentication-security#limits). + Future createPhoneToken( + {required String userId, required String phone}) async { + const String apiPath = '/account/tokens/phone'; + + final Map apiParams = { + 'userId': userId, + 'phone': phone, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification + /// + /// Use this endpoint to send a verification message to your user email address + /// to confirm they are the valid owners of that address. Both the **userId** + /// and **secret** arguments will be passed as query parameters to the URL you + /// have provided to be attached to the verification email. The provided URL + /// should redirect the user back to your app and allow you to complete the + /// verification process by verifying both the **userId** and **secret** + /// parameters. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). + /// The verification link sent to the user's email address is valid for 7 days. + /// + /// Please note that in order to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), + /// the only valid redirect URLs are the ones from domains you have set when + /// adding your platforms in the console interface. + /// + Future createVerification({required String url}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'url': url, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create email verification (confirmation) + /// + /// Use this endpoint to complete the user email verification process. Use both + /// the **userId** and **secret** parameters that were attached to your app URL + /// to verify the user email ownership. If confirmed this route will return a + /// 200 status code. + Future updateVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Create phone verification + /// + /// Use this endpoint to send a verification SMS to the currently logged in + /// user. This endpoint is meant for use after updating a user's phone number + /// using the + /// [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) + /// endpoint. Learn more about how to [complete the verification + /// process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). + /// The verification code sent to the user's phone number is valid for 15 + /// minutes. + Future createPhoneVerification() async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } + + /// Update phone verification (confirmation) + /// + /// Use this endpoint to complete the user phone verification process. Use the + /// **userId** and **secret** that were sent to your user's phone number to + /// verify the user email ownership. If confirmed this route will return a 200 + /// status code. + Future updatePhoneVerification( + {required String userId, required String secret}) async { + const String apiPath = '/account/verification/phone'; + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Token.fromMap(res.data); + } +} diff --git a/lib/services/avatars.dart b/lib/services/avatars.dart index 144c32a3..3bc203e9 100644 --- a/lib/services/avatars.dart +++ b/lib/services/avatars.dart @@ -3,195 +3,203 @@ part of '../appwrite.dart'; /// The Avatars service aims to help you complete everyday tasks related to /// your app image, icons, and avatars. class Avatars extends Service { - /// Initializes a [Avatars] service - Avatars(super.client); - - /// Get browser icon - /// - /// You can use this endpoint to show different browser icons to your users. - /// The code argument receives the browser code as it appears in your user [GET - /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - /// endpoint. Use width, height and quality arguments to change the output - /// settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - Future getBrowser({required enums.Browser code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/browsers/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get credit card icon - /// - /// The credit card endpoint will return you the icon of the credit card - /// provider you need. Use width, height and quality arguments to change the - /// output settings. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getCreditCard({required enums.CreditCard code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get favicon - /// - /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - /// website URL. - /// - /// This endpoint does not follow HTTP redirects. - Future getFavicon({required String url}) async { - const String apiPath = '/avatars/favicon'; - - final Map params = { - - 'url': url, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get country flag - /// - /// You can use this endpoint to show different country flags icons to your - /// users. The code argument receives the 2 letter country code. Use width, - /// height and quality arguments to change the output settings. Country codes - /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getFlag({required enums.Flag code, int? width, int? height, int? quality}) async { - final String apiPath = '/avatars/flags/{code}'.replaceAll('{code}', code.value); - - final Map params = { - - 'width': width, - 'height': height, - 'quality': quality, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get image from URL - /// - /// Use this endpoint to fetch a remote image URL and crop it to any image size - /// you want. This endpoint is very useful if you need to crop and display - /// remote images in your app or in case you want to make sure a 3rd party - /// image is properly served using a TLS protocol. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 400x400px. - /// - /// This endpoint does not follow HTTP redirects. - Future getImage({required String url, int? width, int? height}) async { - const String apiPath = '/avatars/image'; - - final Map params = { - - 'url': url, - 'width': width, - 'height': height, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get user initials - /// - /// Use this endpoint to show your user initials avatar icon on your website or - /// app. By default, this route will try to print your logged-in user name or - /// email initials. You can also overwrite the user name if you pass the 'name' - /// parameter. If no name is given and no user is logged, an empty avatar will - /// be returned. - /// - /// You can use the color and background params to change the avatar colors. By - /// default, a random theme will be selected. The random theme will persist for - /// the user's initials when reloading the same theme will always return for - /// the same initials. - /// - /// When one dimension is specified and the other is 0, the image is scaled - /// with preserved aspect ratio. If both dimensions are 0, the API provides an - /// image at source quality. If dimensions are not specified, the default size - /// of image returned is 100x100px. - /// - Future getInitials({String? name, int? width, int? height, String? background}) async { - const String apiPath = '/avatars/initials'; - - final Map params = { - - 'name': name, - 'width': width, - 'height': height, - 'background': background, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get QR code - /// - /// Converts a given plain text to a QR code image. You can use the query - /// parameters to change the size and style of the resulting image. - /// - Future getQR({required String text, int? size, int? margin, bool? download}) async { - const String apiPath = '/avatars/qr'; - - final Map params = { - - 'text': text, - 'size': size, - 'margin': margin, - 'download': download, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Avatars] service + Avatars(super.client); + + /// Get browser icon + /// + /// You can use this endpoint to show different browser icons to your users. + /// The code argument receives the browser code as it appears in your user [GET + /// /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) + /// endpoint. Use width, height and quality arguments to change the output + /// settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + Future getBrowser( + {required enums.Browser code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/browsers/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get credit card icon + /// + /// The credit card endpoint will return you the icon of the credit card + /// provider you need. Use width, height and quality arguments to change the + /// output settings. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getCreditCard( + {required enums.CreditCard code, + int? width, + int? height, + int? quality}) async { + final String apiPath = + '/avatars/credit-cards/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get favicon + /// + /// Use this endpoint to fetch the favorite icon (AKA favicon) of any remote + /// website URL. + /// + /// This endpoint does not follow HTTP redirects. + Future getFavicon({required String url}) async { + const String apiPath = '/avatars/favicon'; + + final Map params = { + 'url': url, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get country flag + /// + /// You can use this endpoint to show different country flags icons to your + /// users. The code argument receives the 2 letter country code. Use width, + /// height and quality arguments to change the output settings. Country codes + /// follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getFlag( + {required enums.Flag code, int? width, int? height, int? quality}) async { + final String apiPath = + '/avatars/flags/{code}'.replaceAll('{code}', code.value); + + final Map params = { + 'width': width, + 'height': height, + 'quality': quality, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get image from URL + /// + /// Use this endpoint to fetch a remote image URL and crop it to any image size + /// you want. This endpoint is very useful if you need to crop and display + /// remote images in your app or in case you want to make sure a 3rd party + /// image is properly served using a TLS protocol. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 400x400px. + /// + /// This endpoint does not follow HTTP redirects. + Future getImage( + {required String url, int? width, int? height}) async { + const String apiPath = '/avatars/image'; + + final Map params = { + 'url': url, + 'width': width, + 'height': height, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get user initials + /// + /// Use this endpoint to show your user initials avatar icon on your website or + /// app. By default, this route will try to print your logged-in user name or + /// email initials. You can also overwrite the user name if you pass the 'name' + /// parameter. If no name is given and no user is logged, an empty avatar will + /// be returned. + /// + /// You can use the color and background params to change the avatar colors. By + /// default, a random theme will be selected. The random theme will persist for + /// the user's initials when reloading the same theme will always return for + /// the same initials. + /// + /// When one dimension is specified and the other is 0, the image is scaled + /// with preserved aspect ratio. If both dimensions are 0, the API provides an + /// image at source quality. If dimensions are not specified, the default size + /// of image returned is 100x100px. + /// + Future getInitials( + {String? name, int? width, int? height, String? background}) async { + const String apiPath = '/avatars/initials'; + + final Map params = { + 'name': name, + 'width': width, + 'height': height, + 'background': background, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get QR code + /// + /// Converts a given plain text to a QR code image. You can use the query + /// parameters to change the size and style of the resulting image. + /// + Future getQR( + {required String text, int? size, int? margin, bool? download}) async { + const String apiPath = '/avatars/qr'; + + final Map params = { + 'text': text, + 'size': size, + 'margin': margin, + 'download': download, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/databases.dart b/lib/services/databases.dart index 08d3e10b..36f4a1db 100644 --- a/lib/services/databases.dart +++ b/lib/services/databases.dart @@ -3,114 +3,151 @@ part of '../appwrite.dart'; /// The Databases service allows you to create structured collections of /// documents, query and filter lists of documents class Databases extends Service { - /// Initializes a [Databases] service - Databases(super.client); - - /// List documents - /// - /// Get a list of all the user's documents in a given collection. You can use - /// the query params to filter your results. - Future listDocuments({required String databaseId, required String collectionId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.DocumentList.fromMap(res.data); - - } - - /// Create document - /// - /// Create a new Document. Before using this route, you should create a new - /// collection resource using either a [server - /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - /// API or directly from your database console. - Future createDocument({required String databaseId, required String collectionId, required String documentId, required Map data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId); - - final Map apiParams = { - 'documentId': documentId, - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Get document - /// - /// Get a document by its unique ID. This endpoint response returns a JSON - /// object with the document data. - Future getDocument({required String databaseId, required String collectionId, required String documentId, List? queries}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'queries': queries, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Update document - /// - /// Update a document by its unique ID. Using the patch method you can pass - /// only specific fields that will get updated. - Future updateDocument({required String databaseId, required String collectionId, required String documentId, Map? data, List? permissions}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - 'data': data, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Document.fromMap(res.data); - - } - - /// Delete document - /// - /// Delete a document by its unique ID. - Future deleteDocument({required String databaseId, required String collectionId, required String documentId}) async { - final String apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replaceAll('{databaseId}', databaseId).replaceAll('{collectionId}', collectionId).replaceAll('{documentId}', documentId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Databases] service + Databases(super.client); + + /// List documents + /// + /// Get a list of all the user's documents in a given collection. You can use + /// the query params to filter your results. + Future listDocuments( + {required String databaseId, + required String collectionId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.DocumentList.fromMap(res.data); + } + + /// Create document + /// + /// Create a new Document. Before using this route, you should create a new + /// collection resource using either a [server + /// integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) + /// API or directly from your database console. + Future createDocument( + {required String databaseId, + required String collectionId, + required String documentId, + required Map data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId); + + final Map apiParams = { + 'documentId': documentId, + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Get document + /// + /// Get a document by its unique ID. This endpoint response returns a JSON + /// object with the document data. + Future getDocument( + {required String databaseId, + required String collectionId, + required String documentId, + List? queries}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'queries': queries, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Update document + /// + /// Update a document by its unique ID. Using the patch method you can pass + /// only specific fields that will get updated. + Future updateDocument( + {required String databaseId, + required String collectionId, + required String documentId, + Map? data, + List? permissions}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = { + 'data': data, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Document.fromMap(res.data); + } + + /// Delete document + /// + /// Delete a document by its unique ID. + Future deleteDocument( + {required String databaseId, + required String collectionId, + required String documentId}) async { + final String apiPath = + '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}' + .replaceAll('{databaseId}', databaseId) + .replaceAll('{collectionId}', collectionId) + .replaceAll('{documentId}', documentId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/functions.dart b/lib/services/functions.dart index 4ddd6dfe..c78d6294 100644 --- a/lib/services/functions.dart +++ b/lib/services/functions.dart @@ -3,75 +3,89 @@ part of '../appwrite.dart'; /// The Functions Service allows you view, create and manage your Cloud /// Functions. class Functions extends Service { - /// Initializes a [Functions] service - Functions(super.client); - - /// List executions - /// - /// Get a list of all the current user function execution logs. You can use the - /// query params to filter your results. - Future listExecutions({required String functionId, List? queries, String? search}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.ExecutionList.fromMap(res.data); - - } - - /// Create execution - /// - /// Trigger a function execution. The returned object will return you the - /// current execution status. You can ping the `Get Execution` endpoint to get - /// updates on the current execution status. Once this endpoint is called, your - /// function execution process will start asynchronously. - Future createExecution({required String functionId, String? body, bool? xasync, String? path, enums.ExecutionMethod? method, Map? headers, String? scheduledAt}) async { - final String apiPath = '/functions/{functionId}/executions'.replaceAll('{functionId}', functionId); - - final Map apiParams = { - 'body': body, - 'async': xasync, - 'path': path, - 'method': method?.value, - 'headers': headers, - 'scheduledAt': scheduledAt, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } - - /// Get execution - /// - /// Get a function execution log by its unique ID. - Future getExecution({required String functionId, required String executionId}) async { - final String apiPath = '/functions/{functionId}/executions/{executionId}'.replaceAll('{functionId}', functionId).replaceAll('{executionId}', executionId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Execution.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Functions] service + Functions(super.client); + + /// List executions + /// + /// Get a list of all the current user function execution logs. You can use the + /// query params to filter your results. + Future listExecutions( + {required String functionId, + List? queries, + String? search}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.ExecutionList.fromMap(res.data); + } + + /// Create execution + /// + /// Trigger a function execution. The returned object will return you the + /// current execution status. You can ping the `Get Execution` endpoint to get + /// updates on the current execution status. Once this endpoint is called, your + /// function execution process will start asynchronously. + Future createExecution( + {required String functionId, + String? body, + bool? xasync, + String? path, + enums.ExecutionMethod? method, + Map? headers, + String? scheduledAt}) async { + final String apiPath = '/functions/{functionId}/executions' + .replaceAll('{functionId}', functionId); + + final Map apiParams = { + 'body': body, + 'async': xasync, + 'path': path, + 'method': method?.value, + 'headers': headers, + 'scheduledAt': scheduledAt, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } + + /// Get execution + /// + /// Get a function execution log by its unique ID. + Future getExecution( + {required String functionId, required String executionId}) async { + final String apiPath = '/functions/{functionId}/executions/{executionId}' + .replaceAll('{functionId}', functionId) + .replaceAll('{executionId}', executionId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Execution.fromMap(res.data); + } +} diff --git a/lib/services/graphql.dart b/lib/services/graphql.dart index 1e5b32b0..f653df6c 100644 --- a/lib/services/graphql.dart +++ b/lib/services/graphql.dart @@ -3,46 +3,48 @@ part of '../appwrite.dart'; /// The GraphQL API allows you to query and mutate your Appwrite server using /// GraphQL. class Graphql extends Service { - /// Initializes a [Graphql] service - Graphql(super.client); - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future query({required Map query}) async { - const String apiPath = '/graphql'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// GraphQL endpoint - /// - /// Execute a GraphQL mutation. - Future mutation({required Map query}) async { - const String apiPath = '/graphql/mutation'; - - final Map apiParams = { - 'query': query, - }; - - final Map apiHeaders = { - 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Graphql] service + Graphql(super.client); + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future query({required Map query}) async { + const String apiPath = '/graphql'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// GraphQL endpoint + /// + /// Execute a GraphQL mutation. + Future mutation({required Map query}) async { + const String apiPath = '/graphql/mutation'; + + final Map apiParams = { + 'query': query, + }; + + final Map apiHeaders = { + 'x-sdk-graphql': 'true', + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/locale.dart b/lib/services/locale.dart index 8be6f074..6c780391 100644 --- a/lib/services/locale.dart +++ b/lib/services/locale.dart @@ -3,171 +3,163 @@ part of '../appwrite.dart'; /// The Locale service allows you to customize your app based on your users' /// location. class Locale extends Service { - /// Initializes a [Locale] service - Locale(super.client); + /// Initializes a [Locale] service + Locale(super.client); - /// Get user locale - /// - /// Get the current user location based on IP. Returns an object with user - /// country code, country name, continent name, continent code, ip address and - /// suggested currency. You can use the locale header to get the data in a - /// supported language. - /// - /// ([IP Geolocation by DB-IP](https://db-ip.com)) - Future get() async { - const String apiPath = '/locale'; + /// Get user locale + /// + /// Get the current user location based on IP. Returns an object with user + /// country code, country name, continent name, continent code, ip address and + /// suggested currency. You can use the locale header to get the data in a + /// supported language. + /// + /// ([IP Geolocation by DB-IP](https://db-ip.com)) + Future get() async { + const String apiPath = '/locale'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.Locale.fromMap(res.data); + return models.Locale.fromMap(res.data); + } - } + /// List Locale Codes + /// + /// List of all locale codes in [ISO + /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + Future listCodes() async { + const String apiPath = '/locale/codes'; - /// List Locale Codes - /// - /// List of all locale codes in [ISO - /// 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). - Future listCodes() async { - const String apiPath = '/locale/codes'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + return models.LocaleCodeList.fromMap(res.data); + } - return models.LocaleCodeList.fromMap(res.data); + /// List continents + /// + /// List of all continents. You can use the locale header to get the data in a + /// supported language. + Future listContinents() async { + const String apiPath = '/locale/continents'; - } + final Map apiParams = {}; - /// List continents - /// - /// List of all continents. You can use the locale header to get the data in a - /// supported language. - Future listContinents() async { - const String apiPath = '/locale/continents'; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiParams = { - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiHeaders = { - 'content-type': 'application/json', - }; + return models.ContinentList.fromMap(res.data); + } - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + /// List countries + /// + /// List of all countries. You can use the locale header to get the data in a + /// supported language. + Future listCountries() async { + const String apiPath = '/locale/countries'; - return models.ContinentList.fromMap(res.data); + final Map apiParams = {}; - } + final Map apiHeaders = { + 'content-type': 'application/json', + }; - /// List countries - /// - /// List of all countries. You can use the locale header to get the data in a - /// supported language. - Future listCountries() async { - const String apiPath = '/locale/countries'; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final Map apiParams = { - }; + return models.CountryList.fromMap(res.data); + } - final Map apiHeaders = { - 'content-type': 'application/json', - }; + /// List EU countries + /// + /// List of all countries that are currently members of the EU. You can use the + /// locale header to get the data in a supported language. + Future listCountriesEU() async { + const String apiPath = '/locale/countries/eu'; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiParams = {}; - return models.CountryList.fromMap(res.data); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - } + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - /// List EU countries - /// - /// List of all countries that are currently members of the EU. You can use the - /// locale header to get the data in a supported language. - Future listCountriesEU() async { - const String apiPath = '/locale/countries/eu'; + return models.CountryList.fromMap(res.data); + } - final Map apiParams = { - }; + /// List countries phone codes + /// + /// List of all countries phone codes. You can use the locale header to get the + /// data in a supported language. + Future listCountriesPhones() async { + const String apiPath = '/locale/countries/phones'; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiParams = {}; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final Map apiHeaders = { + 'content-type': 'application/json', + }; - return models.CountryList.fromMap(res.data); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - } + return models.PhoneList.fromMap(res.data); + } - /// List countries phone codes - /// - /// List of all countries phone codes. You can use the locale header to get the - /// data in a supported language. - Future listCountriesPhones() async { - const String apiPath = '/locale/countries/phones'; + /// List currencies + /// + /// List of all currencies, including currency symbol, name, plural, and + /// decimal digits for all major and minor currencies. You can use the locale + /// header to get the data in a supported language. + Future listCurrencies() async { + const String apiPath = '/locale/currencies'; - final Map apiParams = { - }; + final Map apiParams = {}; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - return models.PhoneList.fromMap(res.data); + return models.CurrencyList.fromMap(res.data); + } - } + /// List languages + /// + /// List of all languages classified by ISO 639-1 including 2-letter code, name + /// in English, and name in the respective language. + Future listLanguages() async { + const String apiPath = '/locale/languages'; - /// List currencies - /// - /// List of all currencies, including currency symbol, name, plural, and - /// decimal digits for all major and minor currencies. You can use the locale - /// header to get the data in a supported language. - Future listCurrencies() async { - const String apiPath = '/locale/currencies'; + final Map apiParams = {}; - final Map apiParams = { - }; + final Map apiHeaders = { + 'content-type': 'application/json', + }; - final Map apiHeaders = { - 'content-type': 'application/json', - }; + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.CurrencyList.fromMap(res.data); - - } - - /// List languages - /// - /// List of all languages classified by ISO 639-1 including 2-letter code, name - /// in English, and name in the respective language. - Future listLanguages() async { - const String apiPath = '/locale/languages'; - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.LanguageList.fromMap(res.data); - - } -} \ No newline at end of file + return models.LanguageList.fromMap(res.data); + } +} diff --git a/lib/services/messaging.dart b/lib/services/messaging.dart index 30b53556..75a6630c 100644 --- a/lib/services/messaging.dart +++ b/lib/services/messaging.dart @@ -3,46 +3,53 @@ part of '../appwrite.dart'; /// The Messaging service allows you to send messages to any provider type /// (SMTP, push notification, SMS, etc.). class Messaging extends Service { - /// Initializes a [Messaging] service - Messaging(super.client); - - /// Create subscriber - /// - /// Create a new subscriber. - Future createSubscriber({required String topicId, required String subscriberId, required String targetId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers'.replaceAll('{topicId}', topicId); - - final Map apiParams = { - 'subscriberId': subscriberId, - 'targetId': targetId, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Subscriber.fromMap(res.data); - - } - - /// Delete subscriber - /// - /// Delete a subscriber by its unique ID. - Future deleteSubscriber({required String topicId, required String subscriberId}) async { - final String apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replaceAll('{topicId}', topicId).replaceAll('{subscriberId}', subscriberId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } -} \ No newline at end of file + /// Initializes a [Messaging] service + Messaging(super.client); + + /// Create subscriber + /// + /// Create a new subscriber. + Future createSubscriber( + {required String topicId, + required String subscriberId, + required String targetId}) async { + final String apiPath = '/messaging/topics/{topicId}/subscribers' + .replaceAll('{topicId}', topicId); + + final Map apiParams = { + 'subscriberId': subscriberId, + 'targetId': targetId, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Subscriber.fromMap(res.data); + } + + /// Delete subscriber + /// + /// Delete a subscriber by its unique ID. + Future deleteSubscriber( + {required String topicId, required String subscriberId}) async { + final String apiPath = + '/messaging/topics/{topicId}/subscribers/{subscriberId}' + .replaceAll('{topicId}', topicId) + .replaceAll('{subscriberId}', subscriberId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart index be4945cf..d4ba05a2 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -2,208 +2,240 @@ part of '../appwrite.dart'; /// The Storage service allows you to manage your project files. class Storage extends Service { - /// Initializes a [Storage] service - Storage(super.client); - - /// List files - /// - /// Get a list of all the user files. You can use the query params to filter - /// your results. - Future listFiles({required String bucketId, List? queries, String? search}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.FileList.fromMap(res.data); - - } - - /// Create file - /// - /// Create a new file. Before using this route, you should create a new bucket - /// resource using either a [server - /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - /// API or directly from your Appwrite console. - /// - /// Larger files should be uploaded using multiple requests with the - /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - /// header to send a partial request with a maximum supported chunk of `5MB`. - /// The `content-range` header values should always be in bytes. - /// - /// When the first request is sent, the server will return the **File** object, - /// and the subsequent part request must include the file's **id** in - /// `x-appwrite-id` header to allow the server to know that the partial upload - /// is for the existing file and not for a new one. - /// - /// If you're creating a new file using one of the Appwrite SDKs, all the - /// chunking logic will be managed by the SDK internally. - /// - Future createFile({required String bucketId, required String fileId, required InputFile file, List? permissions, Function(UploadProgress)? onProgress}) async { - final String apiPath = '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); - - final Map apiParams = { - - - 'fileId': fileId, - 'file': file, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'multipart/form-data', - }; - - String idParamName = ''; - idParamName = 'fileId'; - final paramName = 'file'; - final res = await client.chunkedUpload( - path: apiPath, - params: apiParams, - paramName: paramName, - idParamName: idParamName, - headers: apiHeaders, - onProgress: onProgress, - ); - - return models.File.fromMap(res.data); - - } - - /// Get file - /// - /// Get a file by its unique ID. This endpoint response returns a JSON object - /// with the file metadata. - Future getFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Update file - /// - /// Update a file by its unique ID. Only users with write permissions have - /// access to update this resource. - Future updateFile({required String bucketId, required String fileId, String? name, List? permissions}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - 'name': name, - 'permissions': permissions, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.File.fromMap(res.data); - - } - - /// Delete File - /// - /// Delete a file by its unique ID. Only users with write permissions have - /// access to delete this resource. - Future deleteFile({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Get file for download - /// - /// Get a file content by its unique ID. The endpoint response return with a - /// 'Content-Disposition: attachment' header that tells the browser to start - /// downloading the file to user downloads directory. - Future getFileDownload({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file preview - /// - /// Get a file preview image. Currently, this method supports preview for image - /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - /// and spreadsheets, will return the file icon image. You can also pass query - /// string arguments for cutting and resizing your preview image. Preview is - /// supported only for image files smaller than 10MB. - Future getFilePreview({required String bucketId, required String fileId, int? width, int? height, enums.ImageGravity? gravity, int? quality, int? borderWidth, String? borderColor, int? borderRadius, double? opacity, int? rotation, String? background, enums.ImageFormat? output}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - 'width': width, - 'height': height, - 'gravity': gravity?.value, - 'quality': quality, - 'borderWidth': borderWidth, - 'borderColor': borderColor, - 'borderRadius': borderRadius, - 'opacity': opacity, - 'rotation': rotation, - 'background': background, - 'output': output?.value, - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } - - /// Get file for view - /// - /// Get a file content by its unique ID. This endpoint is similar to the - /// download method but returns with no 'Content-Disposition: attachment' - /// header. - Future getFileView({required String bucketId, required String fileId}) async { - final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replaceAll('{bucketId}', bucketId).replaceAll('{fileId}', fileId); - - final Map params = { - - - 'project': client.config['project'], - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: params, responseType: ResponseType.bytes); - return res.data; - } -} \ No newline at end of file + /// Initializes a [Storage] service + Storage(super.client); + + /// List files + /// + /// Get a list of all the user files. You can use the query params to filter + /// your results. + Future listFiles( + {required String bucketId, List? queries, String? search}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.FileList.fromMap(res.data); + } + + /// Create file + /// + /// Create a new file. Before using this route, you should create a new bucket + /// resource using either a [server + /// integration](https://appwrite.io/docs/server/storage#storageCreateBucket) + /// API or directly from your Appwrite console. + /// + /// Larger files should be uploaded using multiple requests with the + /// [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) + /// header to send a partial request with a maximum supported chunk of `5MB`. + /// The `content-range` header values should always be in bytes. + /// + /// When the first request is sent, the server will return the **File** object, + /// and the subsequent part request must include the file's **id** in + /// `x-appwrite-id` header to allow the server to know that the partial upload + /// is for the existing file and not for a new one. + /// + /// If you're creating a new file using one of the Appwrite SDKs, all the + /// chunking logic will be managed by the SDK internally. + /// + Future createFile( + {required String bucketId, + required String fileId, + required InputFile file, + List? permissions, + Function(UploadProgress)? onProgress}) async { + final String apiPath = + '/storage/buckets/{bucketId}/files'.replaceAll('{bucketId}', bucketId); + + final Map apiParams = { + 'fileId': fileId, + 'file': file, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'multipart/form-data', + }; + + String idParamName = ''; + idParamName = 'fileId'; + final paramName = 'file'; + final res = await client.chunkedUpload( + path: apiPath, + params: apiParams, + paramName: paramName, + idParamName: idParamName, + headers: apiHeaders, + onProgress: onProgress, + ); + + return models.File.fromMap(res.data); + } + + /// Get file + /// + /// Get a file by its unique ID. This endpoint response returns a JSON object + /// with the file metadata. + Future getFile( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Update file + /// + /// Update a file by its unique ID. Only users with write permissions have + /// access to update this resource. + Future updateFile( + {required String bucketId, + required String fileId, + String? name, + List? permissions}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = { + 'name': name, + 'permissions': permissions, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.File.fromMap(res.data); + } + + /// Delete File + /// + /// Delete a file by its unique ID. Only users with write permissions have + /// access to delete this resource. + Future deleteFile({required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Get file for download + /// + /// Get a file content by its unique ID. The endpoint response return with a + /// 'Content-Disposition: attachment' header that tells the browser to start + /// downloading the file to user downloads directory. + Future getFileDownload( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file preview + /// + /// Get a file preview image. Currently, this method supports preview for image + /// files (jpg, png, and gif), other supported formats, like pdf, docs, slides, + /// and spreadsheets, will return the file icon image. You can also pass query + /// string arguments for cutting and resizing your preview image. Preview is + /// supported only for image files smaller than 10MB. + Future getFilePreview( + {required String bucketId, + required String fileId, + int? width, + int? height, + enums.ImageGravity? gravity, + int? quality, + int? borderWidth, + String? borderColor, + int? borderRadius, + double? opacity, + int? rotation, + String? background, + enums.ImageFormat? output}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'width': width, + 'height': height, + 'gravity': gravity?.value, + 'quality': quality, + 'borderWidth': borderWidth, + 'borderColor': borderColor, + 'borderRadius': borderRadius, + 'opacity': opacity, + 'rotation': rotation, + 'background': background, + 'output': output?.value, + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } + + /// Get file for view + /// + /// Get a file content by its unique ID. This endpoint is similar to the + /// download method but returns with no 'Content-Disposition: attachment' + /// header. + Future getFileView( + {required String bucketId, required String fileId}) async { + final String apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view' + .replaceAll('{bucketId}', bucketId) + .replaceAll('{fileId}', fileId); + + final Map params = { + 'project': client.config['project'], + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: params, responseType: ResponseType.bytes); + return res.data; + } +} diff --git a/lib/services/teams.dart b/lib/services/teams.dart index 21f31e07..a9c7450d 100644 --- a/lib/services/teams.dart +++ b/lib/services/teams.dart @@ -3,312 +3,341 @@ part of '../appwrite.dart'; /// The Teams service allows you to group users of your project and to enable /// them to share read and write access to your project resources class Teams extends Service { - /// Initializes a [Teams] service - Teams(super.client); - - /// List teams - /// - /// Get a list of all the teams in which the current user is a member. You can - /// use the parameters to filter your results. - Future list({List? queries, String? search}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.TeamList.fromMap(res.data); - - } - - /// Create team - /// - /// Create a new team. The user who creates the team will automatically be - /// assigned as the owner of the team. Only the users with the owner role can - /// invite new members, add new owners and delete or update the team. - Future create({required String teamId, required String name, List? roles}) async { - const String apiPath = '/teams'; - - final Map apiParams = { - 'teamId': teamId, - 'name': name, - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Get team - /// - /// Get a team by its ID. All team members have read access for this resource. - Future get({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Update name - /// - /// Update the team's name by its unique ID. - Future updateName({required String teamId, required String name}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Team.fromMap(res.data); - - } - - /// Delete team - /// - /// Delete a team using its ID. Only team members with the owner role can - /// delete the team. - Future delete({required String teamId}) async { - final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// List team memberships - /// - /// Use this endpoint to list a team's members using the team's ID. All team - /// members have read access to this endpoint. - Future listMemberships({required String teamId, List? queries, String? search}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'queries': queries, - 'search': search, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.MembershipList.fromMap(res.data); - - } - - /// Create team membership - /// - /// Invite a new member to join your team. Provide an ID for existing users, or - /// invite unregistered users using an email or phone number. If initiated from - /// a Client SDK, Appwrite will send an email or sms with a link to join the - /// team to the invited user, and an account will be created for them if one - /// doesn't exist. If initiated from a Server SDK, the new member will be added - /// automatically to the team. - /// - /// You only need to provide one of a user ID, email, or phone number. Appwrite - /// will prioritize accepting the user ID > email > phone number if you provide - /// more than one of these parameters. - /// - /// Use the `url` parameter to redirect the user from the invitation email to - /// your app. After the user is redirected, use the [Update Team Membership - /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - /// endpoint to allow the user to accept the invitation to the team. - /// - /// Please note that to avoid a [Redirect - /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - /// Appwrite will accept the only redirect URLs under the domains you have - /// added as a platform on the Appwrite Console. - /// - Future createMembership({required String teamId, required List roles, String? email, String? userId, String? phone, String? url, String? name}) async { - final String apiPath = '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'email': email, - 'userId': userId, - 'phone': phone, - 'roles': roles, - 'url': url, - 'name': name, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.post, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team membership - /// - /// Get a team member by the membership unique id. All team members have read - /// access for this resource. - Future getMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Update membership - /// - /// Modify the roles of a team member. Only team members with the owner role - /// have access to this endpoint. Learn more about [roles and - /// permissions](https://appwrite.io/docs/permissions). - /// - Future updateMembership({required String teamId, required String membershipId, required List roles}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'roles': roles, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Delete team membership - /// - /// This endpoint allows a user to leave a team or for a team owner to delete - /// the membership of any other team member. You can also use this endpoint to - /// delete a user membership even if it is not accepted. - Future deleteMembership({required String teamId, required String membershipId}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.delete, path: apiPath, params: apiParams, headers: apiHeaders); - - return res.data; - - } - - /// Update team membership status - /// - /// Use this endpoint to allow a user to accept an invitation to join a team - /// after being redirected back to your app from the invitation email received - /// by the user. - /// - /// If the request is successful, a session for the user is automatically - /// created. - /// - Future updateMembershipStatus({required String teamId, required String membershipId, required String userId, required String secret}) async { - final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replaceAll('{teamId}', teamId).replaceAll('{membershipId}', membershipId); - - final Map apiParams = { - 'userId': userId, - 'secret': secret, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.patch, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Membership.fromMap(res.data); - - } - - /// Get team preferences - /// - /// Get the team's shared preferences by its unique ID. If a preference doesn't - /// need to be shared by all team members, prefer storing them in [user - /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). - Future getPrefs({required String teamId}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.get, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } - - /// Update preferences - /// - /// Update the team's preferences by its unique ID. The object you pass is - /// stored as is and replaces any previous value. The maximum allowed prefs - /// size is 64kB and throws an error if exceeded. - Future updatePrefs({required String teamId, required Map prefs}) async { - final String apiPath = '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); - - final Map apiParams = { - 'prefs': prefs, - }; - - final Map apiHeaders = { - 'content-type': 'application/json', - }; - - final res = await client.call(HttpMethod.put, path: apiPath, params: apiParams, headers: apiHeaders); - - return models.Preferences.fromMap(res.data); - - } -} \ No newline at end of file + /// Initializes a [Teams] service + Teams(super.client); + + /// List teams + /// + /// Get a list of all the teams in which the current user is a member. You can + /// use the parameters to filter your results. + Future list({List? queries, String? search}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.TeamList.fromMap(res.data); + } + + /// Create team + /// + /// Create a new team. The user who creates the team will automatically be + /// assigned as the owner of the team. Only the users with the owner role can + /// invite new members, add new owners and delete or update the team. + Future create( + {required String teamId, + required String name, + List? roles}) async { + const String apiPath = '/teams'; + + final Map apiParams = { + 'teamId': teamId, + 'name': name, + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Get team + /// + /// Get a team by its ID. All team members have read access for this resource. + Future get({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Update name + /// + /// Update the team's name by its unique ID. + Future updateName( + {required String teamId, required String name}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Team.fromMap(res.data); + } + + /// Delete team + /// + /// Delete a team using its ID. Only team members with the owner role can + /// delete the team. + Future delete({required String teamId}) async { + final String apiPath = '/teams/{teamId}'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// List team memberships + /// + /// Use this endpoint to list a team's members using the team's ID. All team + /// members have read access to this endpoint. + Future listMemberships( + {required String teamId, List? queries, String? search}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'queries': queries, + 'search': search, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.MembershipList.fromMap(res.data); + } + + /// Create team membership + /// + /// Invite a new member to join your team. Provide an ID for existing users, or + /// invite unregistered users using an email or phone number. If initiated from + /// a Client SDK, Appwrite will send an email or sms with a link to join the + /// team to the invited user, and an account will be created for them if one + /// doesn't exist. If initiated from a Server SDK, the new member will be added + /// automatically to the team. + /// + /// You only need to provide one of a user ID, email, or phone number. Appwrite + /// will prioritize accepting the user ID > email > phone number if you provide + /// more than one of these parameters. + /// + /// Use the `url` parameter to redirect the user from the invitation email to + /// your app. After the user is redirected, use the [Update Team Membership + /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) + /// endpoint to allow the user to accept the invitation to the team. + /// + /// Please note that to avoid a [Redirect + /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) + /// Appwrite will accept the only redirect URLs under the domains you have + /// added as a platform on the Appwrite Console. + /// + Future createMembership( + {required String teamId, + required List roles, + String? email, + String? userId, + String? phone, + String? url, + String? name}) async { + final String apiPath = + '/teams/{teamId}/memberships'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'email': email, + 'userId': userId, + 'phone': phone, + 'roles': roles, + 'url': url, + 'name': name, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.post, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team membership + /// + /// Get a team member by the membership unique id. All team members have read + /// access for this resource. + Future getMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Update membership + /// + /// Modify the roles of a team member. Only team members with the owner role + /// have access to this endpoint. Learn more about [roles and + /// permissions](https://appwrite.io/docs/permissions). + /// + Future updateMembership( + {required String teamId, + required String membershipId, + required List roles}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'roles': roles, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Delete team membership + /// + /// This endpoint allows a user to leave a team or for a team owner to delete + /// the membership of any other team member. You can also use this endpoint to + /// delete a user membership even if it is not accepted. + Future deleteMembership( + {required String teamId, required String membershipId}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.delete, + path: apiPath, params: apiParams, headers: apiHeaders); + + return res.data; + } + + /// Update team membership status + /// + /// Use this endpoint to allow a user to accept an invitation to join a team + /// after being redirected back to your app from the invitation email received + /// by the user. + /// + /// If the request is successful, a session for the user is automatically + /// created. + /// + Future updateMembershipStatus( + {required String teamId, + required String membershipId, + required String userId, + required String secret}) async { + final String apiPath = '/teams/{teamId}/memberships/{membershipId}/status' + .replaceAll('{teamId}', teamId) + .replaceAll('{membershipId}', membershipId); + + final Map apiParams = { + 'userId': userId, + 'secret': secret, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.patch, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Membership.fromMap(res.data); + } + + /// Get team preferences + /// + /// Get the team's shared preferences by its unique ID. If a preference doesn't + /// need to be shared by all team members, prefer storing them in [user + /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + Future getPrefs({required String teamId}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = {}; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.get, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } + + /// Update preferences + /// + /// Update the team's preferences by its unique ID. The object you pass is + /// stored as is and replaces any previous value. The maximum allowed prefs + /// size is 64kB and throws an error if exceeded. + Future updatePrefs( + {required String teamId, required Map prefs}) async { + final String apiPath = + '/teams/{teamId}/prefs'.replaceAll('{teamId}', teamId); + + final Map apiParams = { + 'prefs': prefs, + }; + + final Map apiHeaders = { + 'content-type': 'application/json', + }; + + final res = await client.call(HttpMethod.put, + path: apiPath, params: apiParams, headers: apiHeaders); + + return models.Preferences.fromMap(res.data); + } +} diff --git a/lib/src/client.dart b/lib/src/client.dart index 825e24aa..9faffd2f 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -10,7 +10,8 @@ import 'upload_progress.dart'; /// The [Client] is also responsible for managing user's sessions. abstract class Client { /// The size for cunked uploads in bytes. - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; + /// Holds configuration such as project. late Map config; late String _endPoint; @@ -18,6 +19,7 @@ abstract class Client { /// Appwrite endpoint. String get endPoint => _endPoint; + /// Appwrite realtime endpoint. String? get endPointRealtime => _endPointRealtime; @@ -41,7 +43,7 @@ abstract class Client { }); /// Set self signed to [status]. - /// + /// /// If self signed is true, [Client] will ignore invalid certificates. /// This is helpful in environments where your Appwrite /// instance does not have a valid SSL certificate. @@ -75,7 +77,8 @@ abstract class Client { Client addHeader(String key, String value); /// Send the API request. - Future call(HttpMethod method, { + Future call( + HttpMethod method, { String path = '', Map headers = const {}, Map params = const {}, diff --git a/lib/src/client_base.dart b/lib/src/client_base.dart index f94505ab..ed751111 100644 --- a/lib/src/client_base.dart +++ b/lib/src/client_base.dart @@ -2,15 +2,17 @@ import 'response.dart'; import 'client.dart'; import 'enums.dart'; -abstract class ClientBase implements Client { +abstract class ClientBase implements Client { /// Your project ID @override ClientBase setProject(value); + /// Your secret JSON Web Token @override ClientBase setJWT(value); @override ClientBase setLocale(value); + /// The user session to authenticate with @override ClientBase setSession(value); diff --git a/lib/src/client_browser.dart b/lib/src/client_browser.dart index 3bbe39f5..36402189 100644 --- a/lib/src/client_browser.dart +++ b/lib/src/client_browser.dart @@ -19,7 +19,7 @@ ClientBase createClient({ ClientBrowser(endPoint: endPoint, selfSigned: selfSigned); class ClientBrowser extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -64,6 +64,7 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-Project', value); return this; } + /// Your secret JSON Web Token @override ClientBrowser setJWT(value) { @@ -71,12 +72,14 @@ class ClientBrowser extends ClientBase with ClientMixin { addHeader('X-Appwrite-JWT', value); return this; } + @override ClientBrowser setLocale(value) { config['locale'] = value; addHeader('X-Appwrite-Locale', value); return this; } + /// The user session to authenticate with @override ClientBrowser setSession(value) { @@ -138,7 +141,8 @@ class ClientBrowser extends ClientBase with ClientMixin { late Response res; if (size <= CHUNK_SIZE) { - params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!, + filename: file.filename); return call( HttpMethod.post, path: path, @@ -165,8 +169,8 @@ class ClientBrowser extends ClientBase with ClientMixin { List chunk = []; final end = min(offset + CHUNK_SIZE, size); chunk = file.bytes!.getRange(offset, end).toList(); - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, @@ -226,7 +230,7 @@ class ClientBrowser extends ClientBase with ClientMixin { @override Future webAuth(Uri url, {String? callbackUrlScheme}) { - return FlutterWebAuth2.authenticate( + return FlutterWebAuth2.authenticate( url: url.toString(), callbackUrlScheme: "appwrite-callback-" + config['project']!, ); diff --git a/lib/src/client_io.dart b/lib/src/client_io.dart index afdbda28..cab345ff 100644 --- a/lib/src/client_io.dart +++ b/lib/src/client_io.dart @@ -28,7 +28,7 @@ ClientBase createClient({ ); class ClientIO extends ClientBase with ClientMixin { - static const int CHUNK_SIZE = 5*1024*1024; + static const int CHUNK_SIZE = 5 * 1024 * 1024; String _endPoint; Map? _headers; @override @@ -65,7 +65,7 @@ class ClientIO extends ClientBase with ClientMixin { 'x-sdk-platform': 'client', 'x-sdk-language': 'flutter', 'x-sdk-version': '13.0.0', - 'X-Appwrite-Response-Format' : '1.6.0', + 'X-Appwrite-Response-Format': '1.6.0', }; config = {}; @@ -86,33 +86,36 @@ class ClientIO extends ClientBase with ClientMixin { return dir; } - /// Your project ID - @override - ClientIO setProject(value) { - config['project'] = value; - addHeader('X-Appwrite-Project', value); - return this; - } - /// Your secret JSON Web Token - @override - ClientIO setJWT(value) { - config['jWT'] = value; - addHeader('X-Appwrite-JWT', value); - return this; - } - @override - ClientIO setLocale(value) { - config['locale'] = value; - addHeader('X-Appwrite-Locale', value); - return this; - } - /// The user session to authenticate with - @override - ClientIO setSession(value) { - config['session'] = value; - addHeader('X-Appwrite-Session', value); - return this; - } + /// Your project ID + @override + ClientIO setProject(value) { + config['project'] = value; + addHeader('X-Appwrite-Project', value); + return this; + } + + /// Your secret JSON Web Token + @override + ClientIO setJWT(value) { + config['jWT'] = value; + addHeader('X-Appwrite-JWT', value); + return this; + } + + @override + ClientIO setLocale(value) { + config['locale'] = value; + addHeader('X-Appwrite-Locale', value); + return this; + } + + /// The user session to authenticate with + @override + ClientIO setSession(value) { + config['session'] = value; + addHeader('X-Appwrite-Session', value); + return this; + } @override ClientIO setSelfSigned({bool status = true}) { @@ -145,7 +148,7 @@ class ClientIO extends ClientBase with ClientMixin { } Future init() async { - if(_initProgress) return; + if (_initProgress) return; _initProgress = true; final Directory cookieDir = await _getCookiePath(); _cookieJar = PersistCookieJar(storage: FileStorage(cookieDir.path)); @@ -181,13 +184,12 @@ class ClientIO extends ClientBase with ClientMixin { final macinfo = await deviceInfoPlugin.macOsInfo; device = '(Macintosh; ${macinfo.model})'; } - addHeader( - 'user-agent', '${packageInfo.packageName}/${packageInfo.version} $device'); + addHeader('user-agent', + '${packageInfo.packageName}/${packageInfo.version} $device'); } catch (e) { debugPrint('Error getting device info: $e'); device = Platform.operatingSystem; - addHeader( - 'user-agent', '$device'); + addHeader('user-agent', '$device'); } _initialized = true; @@ -296,8 +298,8 @@ class ClientIO extends ClientBase with ClientMixin { raf!.setPositionSync(offset); chunk = raf.readSync(CHUNK_SIZE); } - params[paramName] = - http.MultipartFile.fromBytes(paramName, chunk, filename: file.filename); + params[paramName] = http.MultipartFile.fromBytes(paramName, chunk, + filename: file.filename); headers['content-range'] = 'bytes $offset-${min((offset + CHUNK_SIZE - 1), size - 1)}/$size'; res = await call(HttpMethod.post, diff --git a/lib/src/client_mixin.dart b/lib/src/client_mixin.dart index 36bcdbd3..1078c313 100644 --- a/lib/src/client_mixin.dart +++ b/lib/src/client_mixin.dart @@ -40,7 +40,7 @@ class ClientMixin { } } else if (method == HttpMethod.get) { if (params.isNotEmpty) { - params = params.map((key, value){ + params = params.map((key, value) { if (value is int || value is double) { return MapEntry(key, value.toString()); } @@ -106,18 +106,23 @@ class ClientMixin { return Response(data: data); } - Future toResponse(http.StreamedResponse streamedResponse) async { - if(streamedResponse.statusCode == 204) { - return http.Response('', - streamedResponse.statusCode, - headers: streamedResponse.headers.map((k,v) => k.toLowerCase()=='content-type' ? MapEntry(k, 'text/plain') : MapEntry(k,v)), - request: streamedResponse.request, - isRedirect: streamedResponse.isRedirect, - persistentConnection: streamedResponse.persistentConnection, - reasonPhrase: streamedResponse.reasonPhrase, - ); - } else { - return await http.Response.fromStream(streamedResponse); - } + Future toResponse( + http.StreamedResponse streamedResponse) async { + if (streamedResponse.statusCode == 204) { + return http.Response( + '', + streamedResponse.statusCode, + headers: streamedResponse.headers.map((k, v) => + k.toLowerCase() == 'content-type' + ? MapEntry(k, 'text/plain') + : MapEntry(k, v)), + request: streamedResponse.request, + isRedirect: streamedResponse.isRedirect, + persistentConnection: streamedResponse.persistentConnection, + reasonPhrase: streamedResponse.reasonPhrase, + ); + } else { + return await http.Response.fromStream(streamedResponse); + } } } diff --git a/lib/src/enums/authentication_factor.dart b/lib/src/enums/authentication_factor.dart index 00d12830..1d5271eb 100644 --- a/lib/src/enums/authentication_factor.dart +++ b/lib/src/enums/authentication_factor.dart @@ -1,16 +1,14 @@ part of '../../enums.dart'; enum AuthenticationFactor { - email(value: 'email'), - phone(value: 'phone'), - totp(value: 'totp'), - recoverycode(value: 'recoverycode'); + email(value: 'email'), + phone(value: 'phone'), + totp(value: 'totp'), + recoverycode(value: 'recoverycode'); - const AuthenticationFactor({ - required this.value - }); + const AuthenticationFactor({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/authenticator_type.dart b/lib/src/enums/authenticator_type.dart index 10460393..c1fe8584 100644 --- a/lib/src/enums/authenticator_type.dart +++ b/lib/src/enums/authenticator_type.dart @@ -1,13 +1,11 @@ part of '../../enums.dart'; enum AuthenticatorType { - totp(value: 'totp'); + totp(value: 'totp'); - const AuthenticatorType({ - required this.value - }); + const AuthenticatorType({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/browser.dart b/lib/src/enums/browser.dart index 386fa11d..949f4c47 100644 --- a/lib/src/enums/browser.dart +++ b/lib/src/enums/browser.dart @@ -1,26 +1,24 @@ part of '../../enums.dart'; enum Browser { - avantBrowser(value: 'aa'), - androidWebViewBeta(value: 'an'), - googleChrome(value: 'ch'), - googleChromeIOS(value: 'ci'), - googleChromeMobile(value: 'cm'), - chromium(value: 'cr'), - mozillaFirefox(value: 'ff'), - safari(value: 'sf'), - mobileSafari(value: 'mf'), - microsoftEdge(value: 'ps'), - microsoftEdgeIOS(value: 'oi'), - operaMini(value: 'om'), - opera(value: 'op'), - operaNext(value: 'on'); + avantBrowser(value: 'aa'), + androidWebViewBeta(value: 'an'), + googleChrome(value: 'ch'), + googleChromeIOS(value: 'ci'), + googleChromeMobile(value: 'cm'), + chromium(value: 'cr'), + mozillaFirefox(value: 'ff'), + safari(value: 'sf'), + mobileSafari(value: 'mf'), + microsoftEdge(value: 'ps'), + microsoftEdgeIOS(value: 'oi'), + operaMini(value: 'om'), + opera(value: 'op'), + operaNext(value: 'on'); - const Browser({ - required this.value - }); + const Browser({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/credit_card.dart b/lib/src/enums/credit_card.dart index 7d54fa80..3a6b256a 100644 --- a/lib/src/enums/credit_card.dart +++ b/lib/src/enums/credit_card.dart @@ -1,28 +1,26 @@ part of '../../enums.dart'; enum CreditCard { - americanExpress(value: 'amex'), - argencard(value: 'argencard'), - cabal(value: 'cabal'), - cencosud(value: 'cencosud'), - dinersClub(value: 'diners'), - discover(value: 'discover'), - elo(value: 'elo'), - hipercard(value: 'hipercard'), - jCB(value: 'jcb'), - mastercard(value: 'mastercard'), - naranja(value: 'naranja'), - tarjetaShopping(value: 'targeta-shopping'), - unionChinaPay(value: 'union-china-pay'), - visa(value: 'visa'), - mIR(value: 'mir'), - maestro(value: 'maestro'); + americanExpress(value: 'amex'), + argencard(value: 'argencard'), + cabal(value: 'cabal'), + cencosud(value: 'cencosud'), + dinersClub(value: 'diners'), + discover(value: 'discover'), + elo(value: 'elo'), + hipercard(value: 'hipercard'), + jCB(value: 'jcb'), + mastercard(value: 'mastercard'), + naranja(value: 'naranja'), + tarjetaShopping(value: 'targeta-shopping'), + unionChinaPay(value: 'union-china-pay'), + visa(value: 'visa'), + mIR(value: 'mir'), + maestro(value: 'maestro'); - const CreditCard({ - required this.value - }); + const CreditCard({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/execution_method.dart b/lib/src/enums/execution_method.dart index 7d2d7016..42954430 100644 --- a/lib/src/enums/execution_method.dart +++ b/lib/src/enums/execution_method.dart @@ -1,18 +1,16 @@ part of '../../enums.dart'; enum ExecutionMethod { - gET(value: 'GET'), - pOST(value: 'POST'), - pUT(value: 'PUT'), - pATCH(value: 'PATCH'), - dELETE(value: 'DELETE'), - oPTIONS(value: 'OPTIONS'); + gET(value: 'GET'), + pOST(value: 'POST'), + pUT(value: 'PUT'), + pATCH(value: 'PATCH'), + dELETE(value: 'DELETE'), + oPTIONS(value: 'OPTIONS'); - const ExecutionMethod({ - required this.value - }); + const ExecutionMethod({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/flag.dart b/lib/src/enums/flag.dart index 27c25cac..a44cb81d 100644 --- a/lib/src/enums/flag.dart +++ b/lib/src/enums/flag.dart @@ -1,207 +1,205 @@ part of '../../enums.dart'; enum Flag { - afghanistan(value: 'af'), - angola(value: 'ao'), - albania(value: 'al'), - andorra(value: 'ad'), - unitedArabEmirates(value: 'ae'), - argentina(value: 'ar'), - armenia(value: 'am'), - antiguaAndBarbuda(value: 'ag'), - australia(value: 'au'), - austria(value: 'at'), - azerbaijan(value: 'az'), - burundi(value: 'bi'), - belgium(value: 'be'), - benin(value: 'bj'), - burkinaFaso(value: 'bf'), - bangladesh(value: 'bd'), - bulgaria(value: 'bg'), - bahrain(value: 'bh'), - bahamas(value: 'bs'), - bosniaAndHerzegovina(value: 'ba'), - belarus(value: 'by'), - belize(value: 'bz'), - bolivia(value: 'bo'), - brazil(value: 'br'), - barbados(value: 'bb'), - bruneiDarussalam(value: 'bn'), - bhutan(value: 'bt'), - botswana(value: 'bw'), - centralAfricanRepublic(value: 'cf'), - canada(value: 'ca'), - switzerland(value: 'ch'), - chile(value: 'cl'), - china(value: 'cn'), - coteDIvoire(value: 'ci'), - cameroon(value: 'cm'), - democraticRepublicOfTheCongo(value: 'cd'), - republicOfTheCongo(value: 'cg'), - colombia(value: 'co'), - comoros(value: 'km'), - capeVerde(value: 'cv'), - costaRica(value: 'cr'), - cuba(value: 'cu'), - cyprus(value: 'cy'), - czechRepublic(value: 'cz'), - germany(value: 'de'), - djibouti(value: 'dj'), - dominica(value: 'dm'), - denmark(value: 'dk'), - dominicanRepublic(value: 'do'), - algeria(value: 'dz'), - ecuador(value: 'ec'), - egypt(value: 'eg'), - eritrea(value: 'er'), - spain(value: 'es'), - estonia(value: 'ee'), - ethiopia(value: 'et'), - finland(value: 'fi'), - fiji(value: 'fj'), - france(value: 'fr'), - micronesiaFederatedStatesOf(value: 'fm'), - gabon(value: 'ga'), - unitedKingdom(value: 'gb'), - georgia(value: 'ge'), - ghana(value: 'gh'), - guinea(value: 'gn'), - gambia(value: 'gm'), - guineaBissau(value: 'gw'), - equatorialGuinea(value: 'gq'), - greece(value: 'gr'), - grenada(value: 'gd'), - guatemala(value: 'gt'), - guyana(value: 'gy'), - honduras(value: 'hn'), - croatia(value: 'hr'), - haiti(value: 'ht'), - hungary(value: 'hu'), - indonesia(value: 'id'), - india(value: 'in'), - ireland(value: 'ie'), - iranIslamicRepublicOf(value: 'ir'), - iraq(value: 'iq'), - iceland(value: 'is'), - israel(value: 'il'), - italy(value: 'it'), - jamaica(value: 'jm'), - jordan(value: 'jo'), - japan(value: 'jp'), - kazakhstan(value: 'kz'), - kenya(value: 'ke'), - kyrgyzstan(value: 'kg'), - cambodia(value: 'kh'), - kiribati(value: 'ki'), - saintKittsAndNevis(value: 'kn'), - southKorea(value: 'kr'), - kuwait(value: 'kw'), - laoPeopleSDemocraticRepublic(value: 'la'), - lebanon(value: 'lb'), - liberia(value: 'lr'), - libya(value: 'ly'), - saintLucia(value: 'lc'), - liechtenstein(value: 'li'), - sriLanka(value: 'lk'), - lesotho(value: 'ls'), - lithuania(value: 'lt'), - luxembourg(value: 'lu'), - latvia(value: 'lv'), - morocco(value: 'ma'), - monaco(value: 'mc'), - moldova(value: 'md'), - madagascar(value: 'mg'), - maldives(value: 'mv'), - mexico(value: 'mx'), - marshallIslands(value: 'mh'), - northMacedonia(value: 'mk'), - mali(value: 'ml'), - malta(value: 'mt'), - myanmar(value: 'mm'), - montenegro(value: 'me'), - mongolia(value: 'mn'), - mozambique(value: 'mz'), - mauritania(value: 'mr'), - mauritius(value: 'mu'), - malawi(value: 'mw'), - malaysia(value: 'my'), - namibia(value: 'na'), - niger(value: 'ne'), - nigeria(value: 'ng'), - nicaragua(value: 'ni'), - netherlands(value: 'nl'), - norway(value: 'no'), - nepal(value: 'np'), - nauru(value: 'nr'), - newZealand(value: 'nz'), - oman(value: 'om'), - pakistan(value: 'pk'), - panama(value: 'pa'), - peru(value: 'pe'), - philippines(value: 'ph'), - palau(value: 'pw'), - papuaNewGuinea(value: 'pg'), - poland(value: 'pl'), - frenchPolynesia(value: 'pf'), - northKorea(value: 'kp'), - portugal(value: 'pt'), - paraguay(value: 'py'), - qatar(value: 'qa'), - romania(value: 'ro'), - russia(value: 'ru'), - rwanda(value: 'rw'), - saudiArabia(value: 'sa'), - sudan(value: 'sd'), - senegal(value: 'sn'), - singapore(value: 'sg'), - solomonIslands(value: 'sb'), - sierraLeone(value: 'sl'), - elSalvador(value: 'sv'), - sanMarino(value: 'sm'), - somalia(value: 'so'), - serbia(value: 'rs'), - southSudan(value: 'ss'), - saoTomeAndPrincipe(value: 'st'), - suriname(value: 'sr'), - slovakia(value: 'sk'), - slovenia(value: 'si'), - sweden(value: 'se'), - eswatini(value: 'sz'), - seychelles(value: 'sc'), - syria(value: 'sy'), - chad(value: 'td'), - togo(value: 'tg'), - thailand(value: 'th'), - tajikistan(value: 'tj'), - turkmenistan(value: 'tm'), - timorLeste(value: 'tl'), - tonga(value: 'to'), - trinidadAndTobago(value: 'tt'), - tunisia(value: 'tn'), - turkey(value: 'tr'), - tuvalu(value: 'tv'), - tanzania(value: 'tz'), - uganda(value: 'ug'), - ukraine(value: 'ua'), - uruguay(value: 'uy'), - unitedStates(value: 'us'), - uzbekistan(value: 'uz'), - vaticanCity(value: 'va'), - saintVincentAndTheGrenadines(value: 'vc'), - venezuela(value: 've'), - vietnam(value: 'vn'), - vanuatu(value: 'vu'), - samoa(value: 'ws'), - yemen(value: 'ye'), - southAfrica(value: 'za'), - zambia(value: 'zm'), - zimbabwe(value: 'zw'); + afghanistan(value: 'af'), + angola(value: 'ao'), + albania(value: 'al'), + andorra(value: 'ad'), + unitedArabEmirates(value: 'ae'), + argentina(value: 'ar'), + armenia(value: 'am'), + antiguaAndBarbuda(value: 'ag'), + australia(value: 'au'), + austria(value: 'at'), + azerbaijan(value: 'az'), + burundi(value: 'bi'), + belgium(value: 'be'), + benin(value: 'bj'), + burkinaFaso(value: 'bf'), + bangladesh(value: 'bd'), + bulgaria(value: 'bg'), + bahrain(value: 'bh'), + bahamas(value: 'bs'), + bosniaAndHerzegovina(value: 'ba'), + belarus(value: 'by'), + belize(value: 'bz'), + bolivia(value: 'bo'), + brazil(value: 'br'), + barbados(value: 'bb'), + bruneiDarussalam(value: 'bn'), + bhutan(value: 'bt'), + botswana(value: 'bw'), + centralAfricanRepublic(value: 'cf'), + canada(value: 'ca'), + switzerland(value: 'ch'), + chile(value: 'cl'), + china(value: 'cn'), + coteDIvoire(value: 'ci'), + cameroon(value: 'cm'), + democraticRepublicOfTheCongo(value: 'cd'), + republicOfTheCongo(value: 'cg'), + colombia(value: 'co'), + comoros(value: 'km'), + capeVerde(value: 'cv'), + costaRica(value: 'cr'), + cuba(value: 'cu'), + cyprus(value: 'cy'), + czechRepublic(value: 'cz'), + germany(value: 'de'), + djibouti(value: 'dj'), + dominica(value: 'dm'), + denmark(value: 'dk'), + dominicanRepublic(value: 'do'), + algeria(value: 'dz'), + ecuador(value: 'ec'), + egypt(value: 'eg'), + eritrea(value: 'er'), + spain(value: 'es'), + estonia(value: 'ee'), + ethiopia(value: 'et'), + finland(value: 'fi'), + fiji(value: 'fj'), + france(value: 'fr'), + micronesiaFederatedStatesOf(value: 'fm'), + gabon(value: 'ga'), + unitedKingdom(value: 'gb'), + georgia(value: 'ge'), + ghana(value: 'gh'), + guinea(value: 'gn'), + gambia(value: 'gm'), + guineaBissau(value: 'gw'), + equatorialGuinea(value: 'gq'), + greece(value: 'gr'), + grenada(value: 'gd'), + guatemala(value: 'gt'), + guyana(value: 'gy'), + honduras(value: 'hn'), + croatia(value: 'hr'), + haiti(value: 'ht'), + hungary(value: 'hu'), + indonesia(value: 'id'), + india(value: 'in'), + ireland(value: 'ie'), + iranIslamicRepublicOf(value: 'ir'), + iraq(value: 'iq'), + iceland(value: 'is'), + israel(value: 'il'), + italy(value: 'it'), + jamaica(value: 'jm'), + jordan(value: 'jo'), + japan(value: 'jp'), + kazakhstan(value: 'kz'), + kenya(value: 'ke'), + kyrgyzstan(value: 'kg'), + cambodia(value: 'kh'), + kiribati(value: 'ki'), + saintKittsAndNevis(value: 'kn'), + southKorea(value: 'kr'), + kuwait(value: 'kw'), + laoPeopleSDemocraticRepublic(value: 'la'), + lebanon(value: 'lb'), + liberia(value: 'lr'), + libya(value: 'ly'), + saintLucia(value: 'lc'), + liechtenstein(value: 'li'), + sriLanka(value: 'lk'), + lesotho(value: 'ls'), + lithuania(value: 'lt'), + luxembourg(value: 'lu'), + latvia(value: 'lv'), + morocco(value: 'ma'), + monaco(value: 'mc'), + moldova(value: 'md'), + madagascar(value: 'mg'), + maldives(value: 'mv'), + mexico(value: 'mx'), + marshallIslands(value: 'mh'), + northMacedonia(value: 'mk'), + mali(value: 'ml'), + malta(value: 'mt'), + myanmar(value: 'mm'), + montenegro(value: 'me'), + mongolia(value: 'mn'), + mozambique(value: 'mz'), + mauritania(value: 'mr'), + mauritius(value: 'mu'), + malawi(value: 'mw'), + malaysia(value: 'my'), + namibia(value: 'na'), + niger(value: 'ne'), + nigeria(value: 'ng'), + nicaragua(value: 'ni'), + netherlands(value: 'nl'), + norway(value: 'no'), + nepal(value: 'np'), + nauru(value: 'nr'), + newZealand(value: 'nz'), + oman(value: 'om'), + pakistan(value: 'pk'), + panama(value: 'pa'), + peru(value: 'pe'), + philippines(value: 'ph'), + palau(value: 'pw'), + papuaNewGuinea(value: 'pg'), + poland(value: 'pl'), + frenchPolynesia(value: 'pf'), + northKorea(value: 'kp'), + portugal(value: 'pt'), + paraguay(value: 'py'), + qatar(value: 'qa'), + romania(value: 'ro'), + russia(value: 'ru'), + rwanda(value: 'rw'), + saudiArabia(value: 'sa'), + sudan(value: 'sd'), + senegal(value: 'sn'), + singapore(value: 'sg'), + solomonIslands(value: 'sb'), + sierraLeone(value: 'sl'), + elSalvador(value: 'sv'), + sanMarino(value: 'sm'), + somalia(value: 'so'), + serbia(value: 'rs'), + southSudan(value: 'ss'), + saoTomeAndPrincipe(value: 'st'), + suriname(value: 'sr'), + slovakia(value: 'sk'), + slovenia(value: 'si'), + sweden(value: 'se'), + eswatini(value: 'sz'), + seychelles(value: 'sc'), + syria(value: 'sy'), + chad(value: 'td'), + togo(value: 'tg'), + thailand(value: 'th'), + tajikistan(value: 'tj'), + turkmenistan(value: 'tm'), + timorLeste(value: 'tl'), + tonga(value: 'to'), + trinidadAndTobago(value: 'tt'), + tunisia(value: 'tn'), + turkey(value: 'tr'), + tuvalu(value: 'tv'), + tanzania(value: 'tz'), + uganda(value: 'ug'), + ukraine(value: 'ua'), + uruguay(value: 'uy'), + unitedStates(value: 'us'), + uzbekistan(value: 'uz'), + vaticanCity(value: 'va'), + saintVincentAndTheGrenadines(value: 'vc'), + venezuela(value: 've'), + vietnam(value: 'vn'), + vanuatu(value: 'vu'), + samoa(value: 'ws'), + yemen(value: 'ye'), + southAfrica(value: 'za'), + zambia(value: 'zm'), + zimbabwe(value: 'zw'); - const Flag({ - required this.value - }); + const Flag({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_format.dart b/lib/src/enums/image_format.dart index 66527dfa..2ab5d7b9 100644 --- a/lib/src/enums/image_format.dart +++ b/lib/src/enums/image_format.dart @@ -1,17 +1,15 @@ part of '../../enums.dart'; enum ImageFormat { - jpg(value: 'jpg'), - jpeg(value: 'jpeg'), - gif(value: 'gif'), - png(value: 'png'), - webp(value: 'webp'); + jpg(value: 'jpg'), + jpeg(value: 'jpeg'), + gif(value: 'gif'), + png(value: 'png'), + webp(value: 'webp'); - const ImageFormat({ - required this.value - }); + const ImageFormat({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/image_gravity.dart b/lib/src/enums/image_gravity.dart index 79bc4d62..88029044 100644 --- a/lib/src/enums/image_gravity.dart +++ b/lib/src/enums/image_gravity.dart @@ -1,21 +1,19 @@ part of '../../enums.dart'; enum ImageGravity { - center(value: 'center'), - topLeft(value: 'top-left'), - top(value: 'top'), - topRight(value: 'top-right'), - left(value: 'left'), - right(value: 'right'), - bottomLeft(value: 'bottom-left'), - bottom(value: 'bottom'), - bottomRight(value: 'bottom-right'); + center(value: 'center'), + topLeft(value: 'top-left'), + top(value: 'top'), + topRight(value: 'top-right'), + left(value: 'left'), + right(value: 'right'), + bottomLeft(value: 'bottom-left'), + bottom(value: 'bottom'), + bottomRight(value: 'bottom-right'); - const ImageGravity({ - required this.value - }); + const ImageGravity({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/enums/o_auth_provider.dart b/lib/src/enums/o_auth_provider.dart index b09e9df2..2bc1a82a 100644 --- a/lib/src/enums/o_auth_provider.dart +++ b/lib/src/enums/o_auth_provider.dart @@ -1,51 +1,49 @@ part of '../../enums.dart'; enum OAuthProvider { - amazon(value: 'amazon'), - apple(value: 'apple'), - auth0(value: 'auth0'), - authentik(value: 'authentik'), - autodesk(value: 'autodesk'), - bitbucket(value: 'bitbucket'), - bitly(value: 'bitly'), - box(value: 'box'), - dailymotion(value: 'dailymotion'), - discord(value: 'discord'), - disqus(value: 'disqus'), - dropbox(value: 'dropbox'), - etsy(value: 'etsy'), - facebook(value: 'facebook'), - github(value: 'github'), - gitlab(value: 'gitlab'), - google(value: 'google'), - linkedin(value: 'linkedin'), - microsoft(value: 'microsoft'), - notion(value: 'notion'), - oidc(value: 'oidc'), - okta(value: 'okta'), - paypal(value: 'paypal'), - paypalSandbox(value: 'paypalSandbox'), - podio(value: 'podio'), - salesforce(value: 'salesforce'), - slack(value: 'slack'), - spotify(value: 'spotify'), - stripe(value: 'stripe'), - tradeshift(value: 'tradeshift'), - tradeshiftBox(value: 'tradeshiftBox'), - twitch(value: 'twitch'), - wordpress(value: 'wordpress'), - yahoo(value: 'yahoo'), - yammer(value: 'yammer'), - yandex(value: 'yandex'), - zoho(value: 'zoho'), - zoom(value: 'zoom'), - mock(value: 'mock'); + amazon(value: 'amazon'), + apple(value: 'apple'), + auth0(value: 'auth0'), + authentik(value: 'authentik'), + autodesk(value: 'autodesk'), + bitbucket(value: 'bitbucket'), + bitly(value: 'bitly'), + box(value: 'box'), + dailymotion(value: 'dailymotion'), + discord(value: 'discord'), + disqus(value: 'disqus'), + dropbox(value: 'dropbox'), + etsy(value: 'etsy'), + facebook(value: 'facebook'), + github(value: 'github'), + gitlab(value: 'gitlab'), + google(value: 'google'), + linkedin(value: 'linkedin'), + microsoft(value: 'microsoft'), + notion(value: 'notion'), + oidc(value: 'oidc'), + okta(value: 'okta'), + paypal(value: 'paypal'), + paypalSandbox(value: 'paypalSandbox'), + podio(value: 'podio'), + salesforce(value: 'salesforce'), + slack(value: 'slack'), + spotify(value: 'spotify'), + stripe(value: 'stripe'), + tradeshift(value: 'tradeshift'), + tradeshiftBox(value: 'tradeshiftBox'), + twitch(value: 'twitch'), + wordpress(value: 'wordpress'), + yahoo(value: 'yahoo'), + yammer(value: 'yammer'), + yandex(value: 'yandex'), + zoho(value: 'zoho'), + zoom(value: 'zoom'), + mock(value: 'mock'); - const OAuthProvider({ - required this.value - }); + const OAuthProvider({required this.value}); - final String value; + final String value; - String toJson() => value; -} \ No newline at end of file + String toJson() => value; +} diff --git a/lib/src/exception.dart b/lib/src/exception.dart index 2cc8608b..3d608201 100644 --- a/lib/src/exception.dart +++ b/lib/src/exception.dart @@ -13,7 +13,7 @@ class AppwriteException implements Exception { /// Initializes an Appwrite Exception. AppwriteException([this.message = "", this.code, this.type, this.response]); - + /// Returns the error type, message, and code. @override String toString() { diff --git a/lib/src/models/algo_argon2.dart b/lib/src/models/algo_argon2.dart index 759f320d..4145f701 100644 --- a/lib/src/models/algo_argon2.dart +++ b/lib/src/models/algo_argon2.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoArgon2 class AlgoArgon2 implements Model { - /// Algo type. - final String type; - /// Memory used to compute hash. - final int memoryCost; - /// Amount of time consumed to compute hash - final int timeCost; - /// Number of threads used to compute hash. - final int threads; + /// Algo type. + final String type; - AlgoArgon2({ - required this.type, - required this.memoryCost, - required this.timeCost, - required this.threads, - }); + /// Memory used to compute hash. + final int memoryCost; - factory AlgoArgon2.fromMap(Map map) { - return AlgoArgon2( - type: map['type'].toString(), - memoryCost: map['memoryCost'], - timeCost: map['timeCost'], - threads: map['threads'], - ); - } + /// Amount of time consumed to compute hash + final int timeCost; - Map toMap() { - return { - "type": type, - "memoryCost": memoryCost, - "timeCost": timeCost, - "threads": threads, - }; - } + /// Number of threads used to compute hash. + final int threads; + + AlgoArgon2({ + required this.type, + required this.memoryCost, + required this.timeCost, + required this.threads, + }); + + factory AlgoArgon2.fromMap(Map map) { + return AlgoArgon2( + type: map['type'].toString(), + memoryCost: map['memoryCost'], + timeCost: map['timeCost'], + threads: map['threads'], + ); + } + + Map toMap() { + return { + "type": type, + "memoryCost": memoryCost, + "timeCost": timeCost, + "threads": threads, + }; + } } diff --git a/lib/src/models/algo_bcrypt.dart b/lib/src/models/algo_bcrypt.dart index c9f67200..2ba0c398 100644 --- a/lib/src/models/algo_bcrypt.dart +++ b/lib/src/models/algo_bcrypt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoBcrypt class AlgoBcrypt implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoBcrypt({ - required this.type, - }); + AlgoBcrypt({ + required this.type, + }); - factory AlgoBcrypt.fromMap(Map map) { - return AlgoBcrypt( - type: map['type'].toString(), - ); - } + factory AlgoBcrypt.fromMap(Map map) { + return AlgoBcrypt( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_md5.dart b/lib/src/models/algo_md5.dart index 2fabb416..8bdfca6f 100644 --- a/lib/src/models/algo_md5.dart +++ b/lib/src/models/algo_md5.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoMD5 class AlgoMd5 implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoMd5({ - required this.type, - }); + AlgoMd5({ + required this.type, + }); - factory AlgoMd5.fromMap(Map map) { - return AlgoMd5( - type: map['type'].toString(), - ); - } + factory AlgoMd5.fromMap(Map map) { + return AlgoMd5( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_phpass.dart b/lib/src/models/algo_phpass.dart index fdcee07a..4f5f9179 100644 --- a/lib/src/models/algo_phpass.dart +++ b/lib/src/models/algo_phpass.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoPHPass class AlgoPhpass implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoPhpass({ - required this.type, - }); + AlgoPhpass({ + required this.type, + }); - factory AlgoPhpass.fromMap(Map map) { - return AlgoPhpass( - type: map['type'].toString(), - ); - } + factory AlgoPhpass.fromMap(Map map) { + return AlgoPhpass( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/algo_scrypt.dart b/lib/src/models/algo_scrypt.dart index 5c36373d..fec6f65a 100644 --- a/lib/src/models/algo_scrypt.dart +++ b/lib/src/models/algo_scrypt.dart @@ -2,42 +2,46 @@ part of '../../models.dart'; /// AlgoScrypt class AlgoScrypt implements Model { - /// Algo type. - final String type; - /// CPU complexity of computed hash. - final int costCpu; - /// Memory complexity of computed hash. - final int costMemory; - /// Parallelization of computed hash. - final int costParallel; - /// Length used to compute hash. - final int length; - - AlgoScrypt({ - required this.type, - required this.costCpu, - required this.costMemory, - required this.costParallel, - required this.length, - }); - - factory AlgoScrypt.fromMap(Map map) { - return AlgoScrypt( - type: map['type'].toString(), - costCpu: map['costCpu'], - costMemory: map['costMemory'], - costParallel: map['costParallel'], - length: map['length'], - ); - } - - Map toMap() { - return { - "type": type, - "costCpu": costCpu, - "costMemory": costMemory, - "costParallel": costParallel, - "length": length, - }; - } + /// Algo type. + final String type; + + /// CPU complexity of computed hash. + final int costCpu; + + /// Memory complexity of computed hash. + final int costMemory; + + /// Parallelization of computed hash. + final int costParallel; + + /// Length used to compute hash. + final int length; + + AlgoScrypt({ + required this.type, + required this.costCpu, + required this.costMemory, + required this.costParallel, + required this.length, + }); + + factory AlgoScrypt.fromMap(Map map) { + return AlgoScrypt( + type: map['type'].toString(), + costCpu: map['costCpu'], + costMemory: map['costMemory'], + costParallel: map['costParallel'], + length: map['length'], + ); + } + + Map toMap() { + return { + "type": type, + "costCpu": costCpu, + "costMemory": costMemory, + "costParallel": costParallel, + "length": length, + }; + } } diff --git a/lib/src/models/algo_scrypt_modified.dart b/lib/src/models/algo_scrypt_modified.dart index b10b14a6..0e80700f 100644 --- a/lib/src/models/algo_scrypt_modified.dart +++ b/lib/src/models/algo_scrypt_modified.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// AlgoScryptModified class AlgoScryptModified implements Model { - /// Algo type. - final String type; - /// Salt used to compute hash. - final String salt; - /// Separator used to compute hash. - final String saltSeparator; - /// Key used to compute hash. - final String signerKey; + /// Algo type. + final String type; - AlgoScryptModified({ - required this.type, - required this.salt, - required this.saltSeparator, - required this.signerKey, - }); + /// Salt used to compute hash. + final String salt; - factory AlgoScryptModified.fromMap(Map map) { - return AlgoScryptModified( - type: map['type'].toString(), - salt: map['salt'].toString(), - saltSeparator: map['saltSeparator'].toString(), - signerKey: map['signerKey'].toString(), - ); - } + /// Separator used to compute hash. + final String saltSeparator; - Map toMap() { - return { - "type": type, - "salt": salt, - "saltSeparator": saltSeparator, - "signerKey": signerKey, - }; - } + /// Key used to compute hash. + final String signerKey; + + AlgoScryptModified({ + required this.type, + required this.salt, + required this.saltSeparator, + required this.signerKey, + }); + + factory AlgoScryptModified.fromMap(Map map) { + return AlgoScryptModified( + type: map['type'].toString(), + salt: map['salt'].toString(), + saltSeparator: map['saltSeparator'].toString(), + signerKey: map['signerKey'].toString(), + ); + } + + Map toMap() { + return { + "type": type, + "salt": salt, + "saltSeparator": saltSeparator, + "signerKey": signerKey, + }; + } } diff --git a/lib/src/models/algo_sha.dart b/lib/src/models/algo_sha.dart index 5f3e1654..47068be0 100644 --- a/lib/src/models/algo_sha.dart +++ b/lib/src/models/algo_sha.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// AlgoSHA class AlgoSha implements Model { - /// Algo type. - final String type; + /// Algo type. + final String type; - AlgoSha({ - required this.type, - }); + AlgoSha({ + required this.type, + }); - factory AlgoSha.fromMap(Map map) { - return AlgoSha( - type: map['type'].toString(), - ); - } + factory AlgoSha.fromMap(Map map) { + return AlgoSha( + type: map['type'].toString(), + ); + } - Map toMap() { - return { - "type": type, - }; - } + Map toMap() { + return { + "type": type, + }; + } } diff --git a/lib/src/models/continent.dart b/lib/src/models/continent.dart index e1772f0d..990b1064 100644 --- a/lib/src/models/continent.dart +++ b/lib/src/models/continent.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Continent class Continent implements Model { - /// Continent name. - final String name; - /// Continent two letter code. - final String code; + /// Continent name. + final String name; - Continent({ - required this.name, - required this.code, - }); + /// Continent two letter code. + final String code; - factory Continent.fromMap(Map map) { - return Continent( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Continent({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Continent.fromMap(Map map) { + return Continent( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/continent_list.dart b/lib/src/models/continent_list.dart index d0830aad..fb4ee6f6 100644 --- a/lib/src/models/continent_list.dart +++ b/lib/src/models/continent_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Continents List class ContinentList implements Model { - /// Total number of continents documents that matched your query. - final int total; - /// List of continents. - final List continents; + /// Total number of continents documents that matched your query. + final int total; - ContinentList({ - required this.total, - required this.continents, - }); + /// List of continents. + final List continents; - factory ContinentList.fromMap(Map map) { - return ContinentList( - total: map['total'], - continents: List.from(map['continents'].map((p) => Continent.fromMap(p))), - ); - } + ContinentList({ + required this.total, + required this.continents, + }); - Map toMap() { - return { - "total": total, - "continents": continents.map((p) => p.toMap()).toList(), - }; - } + factory ContinentList.fromMap(Map map) { + return ContinentList( + total: map['total'], + continents: List.from( + map['continents'].map((p) => Continent.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "continents": continents.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/country.dart b/lib/src/models/country.dart index b8757434..d11c55db 100644 --- a/lib/src/models/country.dart +++ b/lib/src/models/country.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Country class Country implements Model { - /// Country name. - final String name; - /// Country two-character ISO 3166-1 alpha code. - final String code; + /// Country name. + final String name; - Country({ - required this.name, - required this.code, - }); + /// Country two-character ISO 3166-1 alpha code. + final String code; - factory Country.fromMap(Map map) { - return Country( - name: map['name'].toString(), - code: map['code'].toString(), - ); - } + Country({ + required this.name, + required this.code, + }); - Map toMap() { - return { - "name": name, - "code": code, - }; - } + factory Country.fromMap(Map map) { + return Country( + name: map['name'].toString(), + code: map['code'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + }; + } } diff --git a/lib/src/models/country_list.dart b/lib/src/models/country_list.dart index 7fa08533..a62f926d 100644 --- a/lib/src/models/country_list.dart +++ b/lib/src/models/country_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Countries List class CountryList implements Model { - /// Total number of countries documents that matched your query. - final int total; - /// List of countries. - final List countries; + /// Total number of countries documents that matched your query. + final int total; - CountryList({ - required this.total, - required this.countries, - }); + /// List of countries. + final List countries; - factory CountryList.fromMap(Map map) { - return CountryList( - total: map['total'], - countries: List.from(map['countries'].map((p) => Country.fromMap(p))), - ); - } + CountryList({ + required this.total, + required this.countries, + }); - Map toMap() { - return { - "total": total, - "countries": countries.map((p) => p.toMap()).toList(), - }; - } + factory CountryList.fromMap(Map map) { + return CountryList( + total: map['total'], + countries: + List.from(map['countries'].map((p) => Country.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "countries": countries.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/currency.dart b/lib/src/models/currency.dart index 11aba951..27eef0c1 100644 --- a/lib/src/models/currency.dart +++ b/lib/src/models/currency.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Currency class Currency implements Model { - /// Currency symbol. - final String symbol; - /// Currency name. - final String name; - /// Currency native symbol. - final String symbolNative; - /// Number of decimal digits. - final int decimalDigits; - /// Currency digit rounding. - final double rounding; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. - final String code; - /// Currency plural name - final String namePlural; - - Currency({ - required this.symbol, - required this.name, - required this.symbolNative, - required this.decimalDigits, - required this.rounding, - required this.code, - required this.namePlural, - }); - - factory Currency.fromMap(Map map) { - return Currency( - symbol: map['symbol'].toString(), - name: map['name'].toString(), - symbolNative: map['symbolNative'].toString(), - decimalDigits: map['decimalDigits'], - rounding: map['rounding'].toDouble(), - code: map['code'].toString(), - namePlural: map['namePlural'].toString(), - ); - } - - Map toMap() { - return { - "symbol": symbol, - "name": name, - "symbolNative": symbolNative, - "decimalDigits": decimalDigits, - "rounding": rounding, - "code": code, - "namePlural": namePlural, - }; - } + /// Currency symbol. + final String symbol; + + /// Currency name. + final String name; + + /// Currency native symbol. + final String symbolNative; + + /// Number of decimal digits. + final int decimalDigits; + + /// Currency digit rounding. + final double rounding; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. + final String code; + + /// Currency plural name + final String namePlural; + + Currency({ + required this.symbol, + required this.name, + required this.symbolNative, + required this.decimalDigits, + required this.rounding, + required this.code, + required this.namePlural, + }); + + factory Currency.fromMap(Map map) { + return Currency( + symbol: map['symbol'].toString(), + name: map['name'].toString(), + symbolNative: map['symbolNative'].toString(), + decimalDigits: map['decimalDigits'], + rounding: map['rounding'].toDouble(), + code: map['code'].toString(), + namePlural: map['namePlural'].toString(), + ); + } + + Map toMap() { + return { + "symbol": symbol, + "name": name, + "symbolNative": symbolNative, + "decimalDigits": decimalDigits, + "rounding": rounding, + "code": code, + "namePlural": namePlural, + }; + } } diff --git a/lib/src/models/currency_list.dart b/lib/src/models/currency_list.dart index cf925bc5..e912ca0a 100644 --- a/lib/src/models/currency_list.dart +++ b/lib/src/models/currency_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Currencies List class CurrencyList implements Model { - /// Total number of currencies documents that matched your query. - final int total; - /// List of currencies. - final List currencies; + /// Total number of currencies documents that matched your query. + final int total; - CurrencyList({ - required this.total, - required this.currencies, - }); + /// List of currencies. + final List currencies; - factory CurrencyList.fromMap(Map map) { - return CurrencyList( - total: map['total'], - currencies: List.from(map['currencies'].map((p) => Currency.fromMap(p))), - ); - } + CurrencyList({ + required this.total, + required this.currencies, + }); - Map toMap() { - return { - "total": total, - "currencies": currencies.map((p) => p.toMap()).toList(), - }; - } + factory CurrencyList.fromMap(Map map) { + return CurrencyList( + total: map['total'], + currencies: List.from( + map['currencies'].map((p) => Currency.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "currencies": currencies.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/document.dart b/lib/src/models/document.dart index d5b8c77e..6406f06a 100644 --- a/lib/src/models/document.dart +++ b/lib/src/models/document.dart @@ -2,53 +2,58 @@ part of '../../models.dart'; /// Document class Document implements Model { - /// Document ID. - final String $id; - /// Collection ID. - final String $collectionId; - /// Database ID. - final String $databaseId; - /// Document creation date in ISO 8601 format. - final String $createdAt; - /// Document update date in ISO 8601 format. - final String $updatedAt; - /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - final Map data; - - Document({ - required this.$id, - required this.$collectionId, - required this.$databaseId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.data, - }); - - factory Document.fromMap(Map map) { - return Document( - $id: map['\$id'].toString(), - $collectionId: map['\$collectionId'].toString(), - $databaseId: map['\$databaseId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - data: map, - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$collectionId": $collectionId, - "\$databaseId": $databaseId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "data": data, - }; - } - - T convertTo(T Function(Map) fromJson) => fromJson(data); + /// Document ID. + final String $id; + + /// Collection ID. + final String $collectionId; + + /// Database ID. + final String $databaseId; + + /// Document creation date in ISO 8601 format. + final String $createdAt; + + /// Document update date in ISO 8601 format. + final String $updatedAt; + + /// Document permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + final Map data; + + Document({ + required this.$id, + required this.$collectionId, + required this.$databaseId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.data, + }); + + factory Document.fromMap(Map map) { + return Document( + $id: map['\$id'].toString(), + $collectionId: map['\$collectionId'].toString(), + $databaseId: map['\$databaseId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + data: map, + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$collectionId": $collectionId, + "\$databaseId": $databaseId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "data": data, + }; + } + + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/document_list.dart b/lib/src/models/document_list.dart index 9d3de14b..b4fd20eb 100644 --- a/lib/src/models/document_list.dart +++ b/lib/src/models/document_list.dart @@ -2,30 +2,32 @@ part of '../../models.dart'; /// Documents List class DocumentList implements Model { - /// Total number of documents documents that matched your query. - final int total; - /// List of documents. - final List documents; + /// Total number of documents documents that matched your query. + final int total; - DocumentList({ - required this.total, - required this.documents, - }); + /// List of documents. + final List documents; - factory DocumentList.fromMap(Map map) { - return DocumentList( - total: map['total'], - documents: List.from(map['documents'].map((p) => Document.fromMap(p))), - ); - } + DocumentList({ + required this.total, + required this.documents, + }); - Map toMap() { - return { - "total": total, - "documents": documents.map((p) => p.toMap()).toList(), - }; - } + factory DocumentList.fromMap(Map map) { + return DocumentList( + total: map['total'], + documents: + List.from(map['documents'].map((p) => Document.fromMap(p))), + ); + } - List convertTo(T Function(Map) fromJson) => - documents.map((d) => d.convertTo(fromJson)).toList(); + Map toMap() { + return { + "total": total, + "documents": documents.map((p) => p.toMap()).toList(), + }; + } + + List convertTo(T Function(Map) fromJson) => + documents.map((d) => d.convertTo(fromJson)).toList(); } diff --git a/lib/src/models/execution.dart b/lib/src/models/execution.dart index 96548ef2..40886cd7 100644 --- a/lib/src/models/execution.dart +++ b/lib/src/models/execution.dart @@ -2,102 +2,120 @@ part of '../../models.dart'; /// Execution class Execution implements Model { - /// Execution ID. - final String $id; - /// Execution creation date in ISO 8601 format. - final String $createdAt; - /// Execution upate date in ISO 8601 format. - final String $updatedAt; - /// Execution roles. - final List $permissions; - /// Function ID. - final String functionId; - /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. - final String trigger; - /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. - final String status; - /// HTTP request method type. - final String requestMethod; - /// HTTP request path and query. - final String requestPath; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List requestHeaders; - /// HTTP response status code. - final int responseStatusCode; - /// HTTP response body. This will return empty unless execution is created as synchronous. - final String responseBody; - /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. - final List responseHeaders; - /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String logs; - /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String errors; - /// Function execution duration in seconds. - final double duration; - /// The scheduled time for execution. If left empty, execution will be queued immediately. - final String? scheduledAt; - - Execution({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.functionId, - required this.trigger, - required this.status, - required this.requestMethod, - required this.requestPath, - required this.requestHeaders, - required this.responseStatusCode, - required this.responseBody, - required this.responseHeaders, - required this.logs, - required this.errors, - required this.duration, - this.scheduledAt, - }); - - factory Execution.fromMap(Map map) { - return Execution( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - functionId: map['functionId'].toString(), - trigger: map['trigger'].toString(), - status: map['status'].toString(), - requestMethod: map['requestMethod'].toString(), - requestPath: map['requestPath'].toString(), - requestHeaders: List.from(map['requestHeaders'].map((p) => Headers.fromMap(p))), - responseStatusCode: map['responseStatusCode'], - responseBody: map['responseBody'].toString(), - responseHeaders: List.from(map['responseHeaders'].map((p) => Headers.fromMap(p))), - logs: map['logs'].toString(), - errors: map['errors'].toString(), - duration: map['duration'].toDouble(), - scheduledAt: map['scheduledAt']?.toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "functionId": functionId, - "trigger": trigger, - "status": status, - "requestMethod": requestMethod, - "requestPath": requestPath, - "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), - "responseStatusCode": responseStatusCode, - "responseBody": responseBody, - "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), - "logs": logs, - "errors": errors, - "duration": duration, - "scheduledAt": scheduledAt, - }; - } + /// Execution ID. + final String $id; + + /// Execution creation date in ISO 8601 format. + final String $createdAt; + + /// Execution upate date in ISO 8601 format. + final String $updatedAt; + + /// Execution roles. + final List $permissions; + + /// Function ID. + final String functionId; + + /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. + final String trigger; + + /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. + final String status; + + /// HTTP request method type. + final String requestMethod; + + /// HTTP request path and query. + final String requestPath; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List requestHeaders; + + /// HTTP response status code. + final int responseStatusCode; + + /// HTTP response body. This will return empty unless execution is created as synchronous. + final String responseBody; + + /// HTTP response headers as a key-value object. This will return only whitelisted headers. All headers are returned if execution is created as synchronous. + final List responseHeaders; + + /// Function logs. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String logs; + + /// Function errors. Includes the last 4,000 characters. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String errors; + + /// Function execution duration in seconds. + final double duration; + + /// The scheduled time for execution. If left empty, execution will be queued immediately. + final String? scheduledAt; + + Execution({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.functionId, + required this.trigger, + required this.status, + required this.requestMethod, + required this.requestPath, + required this.requestHeaders, + required this.responseStatusCode, + required this.responseBody, + required this.responseHeaders, + required this.logs, + required this.errors, + required this.duration, + this.scheduledAt, + }); + + factory Execution.fromMap(Map map) { + return Execution( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + functionId: map['functionId'].toString(), + trigger: map['trigger'].toString(), + status: map['status'].toString(), + requestMethod: map['requestMethod'].toString(), + requestPath: map['requestPath'].toString(), + requestHeaders: List.from( + map['requestHeaders'].map((p) => Headers.fromMap(p))), + responseStatusCode: map['responseStatusCode'], + responseBody: map['responseBody'].toString(), + responseHeaders: List.from( + map['responseHeaders'].map((p) => Headers.fromMap(p))), + logs: map['logs'].toString(), + errors: map['errors'].toString(), + duration: map['duration'].toDouble(), + scheduledAt: map['scheduledAt']?.toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "functionId": functionId, + "trigger": trigger, + "status": status, + "requestMethod": requestMethod, + "requestPath": requestPath, + "requestHeaders": requestHeaders.map((p) => p.toMap()).toList(), + "responseStatusCode": responseStatusCode, + "responseBody": responseBody, + "responseHeaders": responseHeaders.map((p) => p.toMap()).toList(), + "logs": logs, + "errors": errors, + "duration": duration, + "scheduledAt": scheduledAt, + }; + } } diff --git a/lib/src/models/execution_list.dart b/lib/src/models/execution_list.dart index 00333204..32e40531 100644 --- a/lib/src/models/execution_list.dart +++ b/lib/src/models/execution_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Executions List class ExecutionList implements Model { - /// Total number of executions documents that matched your query. - final int total; - /// List of executions. - final List executions; + /// Total number of executions documents that matched your query. + final int total; - ExecutionList({ - required this.total, - required this.executions, - }); + /// List of executions. + final List executions; - factory ExecutionList.fromMap(Map map) { - return ExecutionList( - total: map['total'], - executions: List.from(map['executions'].map((p) => Execution.fromMap(p))), - ); - } + ExecutionList({ + required this.total, + required this.executions, + }); - Map toMap() { - return { - "total": total, - "executions": executions.map((p) => p.toMap()).toList(), - }; - } + factory ExecutionList.fromMap(Map map) { + return ExecutionList( + total: map['total'], + executions: List.from( + map['executions'].map((p) => Execution.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "executions": executions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/file.dart b/lib/src/models/file.dart index a6094782..2e6b9d8f 100644 --- a/lib/src/models/file.dart +++ b/lib/src/models/file.dart @@ -2,72 +2,82 @@ part of '../../models.dart'; /// File class File implements Model { - /// File ID. - final String $id; - /// Bucket ID. - final String bucketId; - /// File creation date in ISO 8601 format. - final String $createdAt; - /// File update date in ISO 8601 format. - final String $updatedAt; - /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). - final List $permissions; - /// File name. - final String name; - /// File MD5 signature. - final String signature; - /// File mime type. - final String mimeType; - /// File original size in bytes. - final int sizeOriginal; - /// Total number of chunks available - final int chunksTotal; - /// Total number of chunks uploaded - final int chunksUploaded; + /// File ID. + final String $id; - File({ - required this.$id, - required this.bucketId, - required this.$createdAt, - required this.$updatedAt, - required this.$permissions, - required this.name, - required this.signature, - required this.mimeType, - required this.sizeOriginal, - required this.chunksTotal, - required this.chunksUploaded, - }); + /// Bucket ID. + final String bucketId; - factory File.fromMap(Map map) { - return File( - $id: map['\$id'].toString(), - bucketId: map['bucketId'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - $permissions: map['\$permissions'] ?? [], - name: map['name'].toString(), - signature: map['signature'].toString(), - mimeType: map['mimeType'].toString(), - sizeOriginal: map['sizeOriginal'], - chunksTotal: map['chunksTotal'], - chunksUploaded: map['chunksUploaded'], - ); - } + /// File creation date in ISO 8601 format. + final String $createdAt; - Map toMap() { - return { - "\$id": $id, - "bucketId": bucketId, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "\$permissions": $permissions, - "name": name, - "signature": signature, - "mimeType": mimeType, - "sizeOriginal": sizeOriginal, - "chunksTotal": chunksTotal, - "chunksUploaded": chunksUploaded, - }; - } + /// File update date in ISO 8601 format. + final String $updatedAt; + + /// File permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + final List $permissions; + + /// File name. + final String name; + + /// File MD5 signature. + final String signature; + + /// File mime type. + final String mimeType; + + /// File original size in bytes. + final int sizeOriginal; + + /// Total number of chunks available + final int chunksTotal; + + /// Total number of chunks uploaded + final int chunksUploaded; + + File({ + required this.$id, + required this.bucketId, + required this.$createdAt, + required this.$updatedAt, + required this.$permissions, + required this.name, + required this.signature, + required this.mimeType, + required this.sizeOriginal, + required this.chunksTotal, + required this.chunksUploaded, + }); + + factory File.fromMap(Map map) { + return File( + $id: map['\$id'].toString(), + bucketId: map['bucketId'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + $permissions: map['\$permissions'] ?? [], + name: map['name'].toString(), + signature: map['signature'].toString(), + mimeType: map['mimeType'].toString(), + sizeOriginal: map['sizeOriginal'], + chunksTotal: map['chunksTotal'], + chunksUploaded: map['chunksUploaded'], + ); + } + + Map toMap() { + return { + "\$id": $id, + "bucketId": bucketId, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "\$permissions": $permissions, + "name": name, + "signature": signature, + "mimeType": mimeType, + "sizeOriginal": sizeOriginal, + "chunksTotal": chunksTotal, + "chunksUploaded": chunksUploaded, + }; + } } diff --git a/lib/src/models/file_list.dart b/lib/src/models/file_list.dart index b0872489..3b695c93 100644 --- a/lib/src/models/file_list.dart +++ b/lib/src/models/file_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Files List class FileList implements Model { - /// Total number of files documents that matched your query. - final int total; - /// List of files. - final List files; + /// Total number of files documents that matched your query. + final int total; - FileList({ - required this.total, - required this.files, - }); + /// List of files. + final List files; - factory FileList.fromMap(Map map) { - return FileList( - total: map['total'], - files: List.from(map['files'].map((p) => File.fromMap(p))), - ); - } + FileList({ + required this.total, + required this.files, + }); - Map toMap() { - return { - "total": total, - "files": files.map((p) => p.toMap()).toList(), - }; - } + factory FileList.fromMap(Map map) { + return FileList( + total: map['total'], + files: List.from(map['files'].map((p) => File.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "files": files.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/headers.dart b/lib/src/models/headers.dart index f03c5ce4..22494998 100644 --- a/lib/src/models/headers.dart +++ b/lib/src/models/headers.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Headers class Headers implements Model { - /// Header name. - final String name; - /// Header value. - final String value; + /// Header name. + final String name; - Headers({ - required this.name, - required this.value, - }); + /// Header value. + final String value; - factory Headers.fromMap(Map map) { - return Headers( - name: map['name'].toString(), - value: map['value'].toString(), - ); - } + Headers({ + required this.name, + required this.value, + }); - Map toMap() { - return { - "name": name, - "value": value, - }; - } + factory Headers.fromMap(Map map) { + return Headers( + name: map['name'].toString(), + value: map['value'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "value": value, + }; + } } diff --git a/lib/src/models/identity.dart b/lib/src/models/identity.dart index 632dc3db..807bdfd0 100644 --- a/lib/src/models/identity.dart +++ b/lib/src/models/identity.dart @@ -2,67 +2,76 @@ part of '../../models.dart'; /// Identity class Identity implements Model { - /// Identity ID. - final String $id; - /// Identity creation date in ISO 8601 format. - final String $createdAt; - /// Identity update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Identity Provider. - final String provider; - /// ID of the User in the Identity Provider. - final String providerUid; - /// Email of the User in the Identity Provider. - final String providerEmail; - /// Identity Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Identity Provider Refresh Token. - final String providerRefreshToken; + /// Identity ID. + final String $id; - Identity({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.provider, - required this.providerUid, - required this.providerEmail, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - }); + /// Identity creation date in ISO 8601 format. + final String $createdAt; - factory Identity.fromMap(Map map) { - return Identity( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerEmail: map['providerEmail'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ); - } + /// Identity update date in ISO 8601 format. + final String $updatedAt; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "provider": provider, - "providerUid": providerUid, - "providerEmail": providerEmail, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - }; - } + /// User ID. + final String userId; + + /// Identity Provider. + final String provider; + + /// ID of the User in the Identity Provider. + final String providerUid; + + /// Email of the User in the Identity Provider. + final String providerEmail; + + /// Identity Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Identity Provider Refresh Token. + final String providerRefreshToken; + + Identity({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.provider, + required this.providerUid, + required this.providerEmail, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + }); + + factory Identity.fromMap(Map map) { + return Identity( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerEmail: map['providerEmail'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "provider": provider, + "providerUid": providerUid, + "providerEmail": providerEmail, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + }; + } } diff --git a/lib/src/models/identity_list.dart b/lib/src/models/identity_list.dart index b38c9775..eab513d8 100644 --- a/lib/src/models/identity_list.dart +++ b/lib/src/models/identity_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Identities List class IdentityList implements Model { - /// Total number of identities documents that matched your query. - final int total; - /// List of identities. - final List identities; + /// Total number of identities documents that matched your query. + final int total; - IdentityList({ - required this.total, - required this.identities, - }); + /// List of identities. + final List identities; - factory IdentityList.fromMap(Map map) { - return IdentityList( - total: map['total'], - identities: List.from(map['identities'].map((p) => Identity.fromMap(p))), - ); - } + IdentityList({ + required this.total, + required this.identities, + }); - Map toMap() { - return { - "total": total, - "identities": identities.map((p) => p.toMap()).toList(), - }; - } + factory IdentityList.fromMap(Map map) { + return IdentityList( + total: map['total'], + identities: List.from( + map['identities'].map((p) => Identity.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "identities": identities.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/jwt.dart b/lib/src/models/jwt.dart index 1b4ff7de..e2e31bd2 100644 --- a/lib/src/models/jwt.dart +++ b/lib/src/models/jwt.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// JWT class Jwt implements Model { - /// JWT encoded string. - final String jwt; + /// JWT encoded string. + final String jwt; - Jwt({ - required this.jwt, - }); + Jwt({ + required this.jwt, + }); - factory Jwt.fromMap(Map map) { - return Jwt( - jwt: map['jwt'].toString(), - ); - } + factory Jwt.fromMap(Map map) { + return Jwt( + jwt: map['jwt'].toString(), + ); + } - Map toMap() { - return { - "jwt": jwt, - }; - } + Map toMap() { + return { + "jwt": jwt, + }; + } } diff --git a/lib/src/models/language.dart b/lib/src/models/language.dart index 6d26c461..b6ec6121 100644 --- a/lib/src/models/language.dart +++ b/lib/src/models/language.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Language class Language implements Model { - /// Language name. - final String name; - /// Language two-character ISO 639-1 codes. - final String code; - /// Language native name. - final String nativeName; + /// Language name. + final String name; - Language({ - required this.name, - required this.code, - required this.nativeName, - }); + /// Language two-character ISO 639-1 codes. + final String code; - factory Language.fromMap(Map map) { - return Language( - name: map['name'].toString(), - code: map['code'].toString(), - nativeName: map['nativeName'].toString(), - ); - } + /// Language native name. + final String nativeName; - Map toMap() { - return { - "name": name, - "code": code, - "nativeName": nativeName, - }; - } + Language({ + required this.name, + required this.code, + required this.nativeName, + }); + + factory Language.fromMap(Map map) { + return Language( + name: map['name'].toString(), + code: map['code'].toString(), + nativeName: map['nativeName'].toString(), + ); + } + + Map toMap() { + return { + "name": name, + "code": code, + "nativeName": nativeName, + }; + } } diff --git a/lib/src/models/language_list.dart b/lib/src/models/language_list.dart index c6977a0e..29f49481 100644 --- a/lib/src/models/language_list.dart +++ b/lib/src/models/language_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Languages List class LanguageList implements Model { - /// Total number of languages documents that matched your query. - final int total; - /// List of languages. - final List languages; + /// Total number of languages documents that matched your query. + final int total; - LanguageList({ - required this.total, - required this.languages, - }); + /// List of languages. + final List languages; - factory LanguageList.fromMap(Map map) { - return LanguageList( - total: map['total'], - languages: List.from(map['languages'].map((p) => Language.fromMap(p))), - ); - } + LanguageList({ + required this.total, + required this.languages, + }); - Map toMap() { - return { - "total": total, - "languages": languages.map((p) => p.toMap()).toList(), - }; - } + factory LanguageList.fromMap(Map map) { + return LanguageList( + total: map['total'], + languages: + List.from(map['languages'].map((p) => Language.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "languages": languages.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 0f0fd7f2..084475bf 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -2,52 +2,58 @@ part of '../../models.dart'; /// Locale class Locale implements Model { - /// User IP address. - final String ip; - /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format - final String countryCode; - /// Country name. This field support localization. - final String country; - /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. - final String continentCode; - /// Continent name. This field support localization. - final String continent; - /// True if country is part of the European Union. - final bool eu; - /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format - final String currency; - - Locale({ - required this.ip, - required this.countryCode, - required this.country, - required this.continentCode, - required this.continent, - required this.eu, - required this.currency, - }); - - factory Locale.fromMap(Map map) { - return Locale( - ip: map['ip'].toString(), - countryCode: map['countryCode'].toString(), - country: map['country'].toString(), - continentCode: map['continentCode'].toString(), - continent: map['continent'].toString(), - eu: map['eu'], - currency: map['currency'].toString(), - ); - } - - Map toMap() { - return { - "ip": ip, - "countryCode": countryCode, - "country": country, - "continentCode": continentCode, - "continent": continent, - "eu": eu, - "currency": currency, - }; - } + /// User IP address. + final String ip; + + /// Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format + final String countryCode; + + /// Country name. This field support localization. + final String country; + + /// Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + final String continentCode; + + /// Continent name. This field support localization. + final String continent; + + /// True if country is part of the European Union. + final bool eu; + + /// Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format + final String currency; + + Locale({ + required this.ip, + required this.countryCode, + required this.country, + required this.continentCode, + required this.continent, + required this.eu, + required this.currency, + }); + + factory Locale.fromMap(Map map) { + return Locale( + ip: map['ip'].toString(), + countryCode: map['countryCode'].toString(), + country: map['country'].toString(), + continentCode: map['continentCode'].toString(), + continent: map['continent'].toString(), + eu: map['eu'], + currency: map['currency'].toString(), + ); + } + + Map toMap() { + return { + "ip": ip, + "countryCode": countryCode, + "country": country, + "continentCode": continentCode, + "continent": continent, + "eu": eu, + "currency": currency, + }; + } } diff --git a/lib/src/models/locale_code.dart b/lib/src/models/locale_code.dart index eebce199..678e40c4 100644 --- a/lib/src/models/locale_code.dart +++ b/lib/src/models/locale_code.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// LocaleCode class LocaleCode implements Model { - /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - final String code; - /// Locale name - final String name; + /// Locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + final String code; - LocaleCode({ - required this.code, - required this.name, - }); + /// Locale name + final String name; - factory LocaleCode.fromMap(Map map) { - return LocaleCode( - code: map['code'].toString(), - name: map['name'].toString(), - ); - } + LocaleCode({ + required this.code, + required this.name, + }); - Map toMap() { - return { - "code": code, - "name": name, - }; - } + factory LocaleCode.fromMap(Map map) { + return LocaleCode( + code: map['code'].toString(), + name: map['name'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "name": name, + }; + } } diff --git a/lib/src/models/locale_code_list.dart b/lib/src/models/locale_code_list.dart index 090b332d..c3f4e4be 100644 --- a/lib/src/models/locale_code_list.dart +++ b/lib/src/models/locale_code_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Locale codes list class LocaleCodeList implements Model { - /// Total number of localeCodes documents that matched your query. - final int total; - /// List of localeCodes. - final List localeCodes; + /// Total number of localeCodes documents that matched your query. + final int total; - LocaleCodeList({ - required this.total, - required this.localeCodes, - }); + /// List of localeCodes. + final List localeCodes; - factory LocaleCodeList.fromMap(Map map) { - return LocaleCodeList( - total: map['total'], - localeCodes: List.from(map['localeCodes'].map((p) => LocaleCode.fromMap(p))), - ); - } + LocaleCodeList({ + required this.total, + required this.localeCodes, + }); - Map toMap() { - return { - "total": total, - "localeCodes": localeCodes.map((p) => p.toMap()).toList(), - }; - } + factory LocaleCodeList.fromMap(Map map) { + return LocaleCodeList( + total: map['total'], + localeCodes: List.from( + map['localeCodes'].map((p) => LocaleCode.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "localeCodes": localeCodes.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/log.dart b/lib/src/models/log.dart index 41cda2ca..7fb3f364 100644 --- a/lib/src/models/log.dart +++ b/lib/src/models/log.dart @@ -2,122 +2,142 @@ part of '../../models.dart'; /// Log class Log implements Model { - /// Event name. - final String event; - /// User ID. - final String userId; - /// User Email. - final String userEmail; - /// User Name. - final String userName; - /// API mode when event triggered. - final String mode; - /// IP session in use when the session was created. - final String ip; - /// Log creation date in ISO 8601 format. - final String time; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - - Log({ - required this.event, - required this.userId, - required this.userEmail, - required this.userName, - required this.mode, - required this.ip, - required this.time, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - }); - - factory Log.fromMap(Map map) { - return Log( - event: map['event'].toString(), - userId: map['userId'].toString(), - userEmail: map['userEmail'].toString(), - userName: map['userName'].toString(), - mode: map['mode'].toString(), - ip: map['ip'].toString(), - time: map['time'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } - - Map toMap() { - return { - "event": event, - "userId": userId, - "userEmail": userEmail, - "userName": userName, - "mode": mode, - "ip": ip, - "time": time, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - }; - } + /// Event name. + final String event; + + /// User ID. + final String userId; + + /// User Email. + final String userEmail; + + /// User Name. + final String userName; + + /// API mode when event triggered. + final String mode; + + /// IP session in use when the session was created. + final String ip; + + /// Log creation date in ISO 8601 format. + final String time; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + Log({ + required this.event, + required this.userId, + required this.userEmail, + required this.userName, + required this.mode, + required this.ip, + required this.time, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + }); + + factory Log.fromMap(Map map) { + return Log( + event: map['event'].toString(), + userId: map['userId'].toString(), + userEmail: map['userEmail'].toString(), + userName: map['userName'].toString(), + mode: map['mode'].toString(), + ip: map['ip'].toString(), + time: map['time'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "event": event, + "userId": userId, + "userEmail": userEmail, + "userName": userName, + "mode": mode, + "ip": ip, + "time": time, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/log_list.dart b/lib/src/models/log_list.dart index 9af5b1cd..a686897c 100644 --- a/lib/src/models/log_list.dart +++ b/lib/src/models/log_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Logs List class LogList implements Model { - /// Total number of logs documents that matched your query. - final int total; - /// List of logs. - final List logs; + /// Total number of logs documents that matched your query. + final int total; - LogList({ - required this.total, - required this.logs, - }); + /// List of logs. + final List logs; - factory LogList.fromMap(Map map) { - return LogList( - total: map['total'], - logs: List.from(map['logs'].map((p) => Log.fromMap(p))), - ); - } + LogList({ + required this.total, + required this.logs, + }); - Map toMap() { - return { - "total": total, - "logs": logs.map((p) => p.toMap()).toList(), - }; - } + factory LogList.fromMap(Map map) { + return LogList( + total: map['total'], + logs: List.from(map['logs'].map((p) => Log.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "logs": logs.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/membership.dart b/lib/src/models/membership.dart index 283f4ee5..fb3fb523 100644 --- a/lib/src/models/membership.dart +++ b/lib/src/models/membership.dart @@ -2,82 +2,94 @@ part of '../../models.dart'; /// Membership class Membership implements Model { - /// Membership ID. - final String $id; - /// Membership creation date in ISO 8601 format. - final String $createdAt; - /// Membership update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// User name. - final String userName; - /// User email address. - final String userEmail; - /// Team ID. - final String teamId; - /// Team name. - final String teamName; - /// Date, the user has been invited to join the team in ISO 8601 format. - final String invited; - /// Date, the user has accepted the invitation to join the team in ISO 8601 format. - final String joined; - /// User confirmation status, true if the user has joined the team or false otherwise. - final bool confirm; - /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. - final bool mfa; - /// User list of roles - final List roles; - - Membership({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.userName, - required this.userEmail, - required this.teamId, - required this.teamName, - required this.invited, - required this.joined, - required this.confirm, - required this.mfa, - required this.roles, - }); - - factory Membership.fromMap(Map map) { - return Membership( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - userEmail: map['userEmail'].toString(), - teamId: map['teamId'].toString(), - teamName: map['teamName'].toString(), - invited: map['invited'].toString(), - joined: map['joined'].toString(), - confirm: map['confirm'], - mfa: map['mfa'], - roles: map['roles'] ?? [], - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "userName": userName, - "userEmail": userEmail, - "teamId": teamId, - "teamName": teamName, - "invited": invited, - "joined": joined, - "confirm": confirm, - "mfa": mfa, - "roles": roles, - }; - } + /// Membership ID. + final String $id; + + /// Membership creation date in ISO 8601 format. + final String $createdAt; + + /// Membership update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// User name. + final String userName; + + /// User email address. + final String userEmail; + + /// Team ID. + final String teamId; + + /// Team name. + final String teamName; + + /// Date, the user has been invited to join the team in ISO 8601 format. + final String invited; + + /// Date, the user has accepted the invitation to join the team in ISO 8601 format. + final String joined; + + /// User confirmation status, true if the user has joined the team or false otherwise. + final bool confirm; + + /// Multi factor authentication status, true if the user has MFA enabled or false otherwise. + final bool mfa; + + /// User list of roles + final List roles; + + Membership({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.userName, + required this.userEmail, + required this.teamId, + required this.teamName, + required this.invited, + required this.joined, + required this.confirm, + required this.mfa, + required this.roles, + }); + + factory Membership.fromMap(Map map) { + return Membership( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + userEmail: map['userEmail'].toString(), + teamId: map['teamId'].toString(), + teamName: map['teamName'].toString(), + invited: map['invited'].toString(), + joined: map['joined'].toString(), + confirm: map['confirm'], + mfa: map['mfa'], + roles: map['roles'] ?? [], + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "userName": userName, + "userEmail": userEmail, + "teamId": teamId, + "teamName": teamName, + "invited": invited, + "joined": joined, + "confirm": confirm, + "mfa": mfa, + "roles": roles, + }; + } } diff --git a/lib/src/models/membership_list.dart b/lib/src/models/membership_list.dart index 1da7cd60..ee65133b 100644 --- a/lib/src/models/membership_list.dart +++ b/lib/src/models/membership_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Memberships List class MembershipList implements Model { - /// Total number of memberships documents that matched your query. - final int total; - /// List of memberships. - final List memberships; + /// Total number of memberships documents that matched your query. + final int total; - MembershipList({ - required this.total, - required this.memberships, - }); + /// List of memberships. + final List memberships; - factory MembershipList.fromMap(Map map) { - return MembershipList( - total: map['total'], - memberships: List.from(map['memberships'].map((p) => Membership.fromMap(p))), - ); - } + MembershipList({ + required this.total, + required this.memberships, + }); - Map toMap() { - return { - "total": total, - "memberships": memberships.map((p) => p.toMap()).toList(), - }; - } + factory MembershipList.fromMap(Map map) { + return MembershipList( + total: map['total'], + memberships: List.from( + map['memberships'].map((p) => Membership.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "memberships": memberships.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/mfa_challenge.dart b/lib/src/models/mfa_challenge.dart index 043ff286..96bf3c65 100644 --- a/lib/src/models/mfa_challenge.dart +++ b/lib/src/models/mfa_challenge.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFA Challenge class MfaChallenge implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token expiration date in ISO 8601 format. - final String expire; + /// Token ID. + final String $id; - MfaChallenge({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.expire, - }); + /// Token creation date in ISO 8601 format. + final String $createdAt; - factory MfaChallenge.fromMap(Map map) { - return MfaChallenge( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - ); - } + /// User ID. + final String userId; - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "expire": expire, - }; - } + /// Token expiration date in ISO 8601 format. + final String expire; + + MfaChallenge({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.expire, + }); + + factory MfaChallenge.fromMap(Map map) { + return MfaChallenge( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "expire": expire, + }; + } } diff --git a/lib/src/models/mfa_factors.dart b/lib/src/models/mfa_factors.dart index f453e870..c930a23e 100644 --- a/lib/src/models/mfa_factors.dart +++ b/lib/src/models/mfa_factors.dart @@ -2,37 +2,40 @@ part of '../../models.dart'; /// MFAFactors class MfaFactors implements Model { - /// Can TOTP be used for MFA challenge for this account. - final bool totp; - /// Can phone (SMS) be used for MFA challenge for this account. - final bool phone; - /// Can email be used for MFA challenge for this account. - final bool email; - /// Can recovery code be used for MFA challenge for this account. - final bool recoveryCode; + /// Can TOTP be used for MFA challenge for this account. + final bool totp; - MfaFactors({ - required this.totp, - required this.phone, - required this.email, - required this.recoveryCode, - }); + /// Can phone (SMS) be used for MFA challenge for this account. + final bool phone; - factory MfaFactors.fromMap(Map map) { - return MfaFactors( - totp: map['totp'], - phone: map['phone'], - email: map['email'], - recoveryCode: map['recoveryCode'], - ); - } + /// Can email be used for MFA challenge for this account. + final bool email; - Map toMap() { - return { - "totp": totp, - "phone": phone, - "email": email, - "recoveryCode": recoveryCode, - }; - } + /// Can recovery code be used for MFA challenge for this account. + final bool recoveryCode; + + MfaFactors({ + required this.totp, + required this.phone, + required this.email, + required this.recoveryCode, + }); + + factory MfaFactors.fromMap(Map map) { + return MfaFactors( + totp: map['totp'], + phone: map['phone'], + email: map['email'], + recoveryCode: map['recoveryCode'], + ); + } + + Map toMap() { + return { + "totp": totp, + "phone": phone, + "email": email, + "recoveryCode": recoveryCode, + }; + } } diff --git a/lib/src/models/mfa_recovery_codes.dart b/lib/src/models/mfa_recovery_codes.dart index 68402443..83483901 100644 --- a/lib/src/models/mfa_recovery_codes.dart +++ b/lib/src/models/mfa_recovery_codes.dart @@ -2,22 +2,22 @@ part of '../../models.dart'; /// MFA Recovery Codes class MfaRecoveryCodes implements Model { - /// Recovery codes. - final List recoveryCodes; + /// Recovery codes. + final List recoveryCodes; - MfaRecoveryCodes({ - required this.recoveryCodes, - }); + MfaRecoveryCodes({ + required this.recoveryCodes, + }); - factory MfaRecoveryCodes.fromMap(Map map) { - return MfaRecoveryCodes( - recoveryCodes: map['recoveryCodes'] ?? [], - ); - } + factory MfaRecoveryCodes.fromMap(Map map) { + return MfaRecoveryCodes( + recoveryCodes: map['recoveryCodes'] ?? [], + ); + } - Map toMap() { - return { - "recoveryCodes": recoveryCodes, - }; - } + Map toMap() { + return { + "recoveryCodes": recoveryCodes, + }; + } } diff --git a/lib/src/models/mfa_type.dart b/lib/src/models/mfa_type.dart index 87064007..0573166e 100644 --- a/lib/src/models/mfa_type.dart +++ b/lib/src/models/mfa_type.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// MFAType class MfaType implements Model { - /// Secret token used for TOTP factor. - final String secret; - /// URI for authenticator apps. - final String uri; + /// Secret token used for TOTP factor. + final String secret; - MfaType({ - required this.secret, - required this.uri, - }); + /// URI for authenticator apps. + final String uri; - factory MfaType.fromMap(Map map) { - return MfaType( - secret: map['secret'].toString(), - uri: map['uri'].toString(), - ); - } + MfaType({ + required this.secret, + required this.uri, + }); - Map toMap() { - return { - "secret": secret, - "uri": uri, - }; - } + factory MfaType.fromMap(Map map) { + return MfaType( + secret: map['secret'].toString(), + uri: map['uri'].toString(), + ); + } + + Map toMap() { + return { + "secret": secret, + "uri": uri, + }; + } } diff --git a/lib/src/models/model.dart b/lib/src/models/model.dart index 48e5b84a..f810a35b 100644 --- a/lib/src/models/model.dart +++ b/lib/src/models/model.dart @@ -2,4 +2,4 @@ part of '../../models.dart'; abstract class Model { Map toMap(); -} \ No newline at end of file +} diff --git a/lib/src/models/phone.dart b/lib/src/models/phone.dart index 24f7260d..40f7bcd2 100644 --- a/lib/src/models/phone.dart +++ b/lib/src/models/phone.dart @@ -2,32 +2,34 @@ part of '../../models.dart'; /// Phone class Phone implements Model { - /// Phone code. - final String code; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; + /// Phone code. + final String code; - Phone({ - required this.code, - required this.countryCode, - required this.countryName, - }); + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; - factory Phone.fromMap(Map map) { - return Phone( - code: map['code'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - ); - } + /// Country name. + final String countryName; - Map toMap() { - return { - "code": code, - "countryCode": countryCode, - "countryName": countryName, - }; - } + Phone({ + required this.code, + required this.countryCode, + required this.countryName, + }); + + factory Phone.fromMap(Map map) { + return Phone( + code: map['code'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + ); + } + + Map toMap() { + return { + "code": code, + "countryCode": countryCode, + "countryName": countryName, + }; + } } diff --git a/lib/src/models/phone_list.dart b/lib/src/models/phone_list.dart index 55e6108e..1ae5a351 100644 --- a/lib/src/models/phone_list.dart +++ b/lib/src/models/phone_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Phones List class PhoneList implements Model { - /// Total number of phones documents that matched your query. - final int total; - /// List of phones. - final List phones; + /// Total number of phones documents that matched your query. + final int total; - PhoneList({ - required this.total, - required this.phones, - }); + /// List of phones. + final List phones; - factory PhoneList.fromMap(Map map) { - return PhoneList( - total: map['total'], - phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), - ); - } + PhoneList({ + required this.total, + required this.phones, + }); - Map toMap() { - return { - "total": total, - "phones": phones.map((p) => p.toMap()).toList(), - }; - } + factory PhoneList.fromMap(Map map) { + return PhoneList( + total: map['total'], + phones: List.from(map['phones'].map((p) => Phone.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "phones": phones.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/preferences.dart b/lib/src/models/preferences.dart index 3c62f86d..3549cff0 100644 --- a/lib/src/models/preferences.dart +++ b/lib/src/models/preferences.dart @@ -2,23 +2,23 @@ part of '../../models.dart'; /// Preferences class Preferences implements Model { - final Map data; + final Map data; - Preferences({ - required this.data, - }); + Preferences({ + required this.data, + }); - factory Preferences.fromMap(Map map) { - return Preferences( - data: map, - ); - } + factory Preferences.fromMap(Map map) { + return Preferences( + data: map, + ); + } - Map toMap() { - return { - "data": data, - }; - } + Map toMap() { + return { + "data": data, + }; + } - T convertTo(T Function(Map) fromJson) => fromJson(data); + T convertTo(T Function(Map) fromJson) => fromJson(data); } diff --git a/lib/src/models/session.dart b/lib/src/models/session.dart index 10566f44..1f55d400 100644 --- a/lib/src/models/session.dart +++ b/lib/src/models/session.dart @@ -2,162 +2,190 @@ part of '../../models.dart'; /// Session class Session implements Model { - /// Session ID. - final String $id; - /// Session creation date in ISO 8601 format. - final String $createdAt; - /// Session update date in ISO 8601 format. - final String $updatedAt; - /// User ID. - final String userId; - /// Session expiration date in ISO 8601 format. - final String expire; - /// Session Provider. - final String provider; - /// Session Provider User ID. - final String providerUid; - /// Session Provider Access Token. - final String providerAccessToken; - /// The date of when the access token expires in ISO 8601 format. - final String providerAccessTokenExpiry; - /// Session Provider Refresh Token. - final String providerRefreshToken; - /// IP in use when the session was created. - final String ip; - /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). - final String osCode; - /// Operating system name. - final String osName; - /// Operating system version. - final String osVersion; - /// Client type. - final String clientType; - /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). - final String clientCode; - /// Client name. - final String clientName; - /// Client version. - final String clientVersion; - /// Client engine name. - final String clientEngine; - /// Client engine name. - final String clientEngineVersion; - /// Device name. - final String deviceName; - /// Device brand name. - final String deviceBrand; - /// Device model name. - final String deviceModel; - /// Country two-character ISO 3166-1 alpha code. - final String countryCode; - /// Country name. - final String countryName; - /// Returns true if this the current user session. - final bool current; - /// Returns a list of active session factors. - final List factors; - /// Secret used to authenticate the user. Only included if the request was made with an API key - final String secret; - /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. - final String mfaUpdatedAt; - - Session({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.userId, - required this.expire, - required this.provider, - required this.providerUid, - required this.providerAccessToken, - required this.providerAccessTokenExpiry, - required this.providerRefreshToken, - required this.ip, - required this.osCode, - required this.osName, - required this.osVersion, - required this.clientType, - required this.clientCode, - required this.clientName, - required this.clientVersion, - required this.clientEngine, - required this.clientEngineVersion, - required this.deviceName, - required this.deviceBrand, - required this.deviceModel, - required this.countryCode, - required this.countryName, - required this.current, - required this.factors, - required this.secret, - required this.mfaUpdatedAt, - }); - - factory Session.fromMap(Map map) { - return Session( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - userId: map['userId'].toString(), - expire: map['expire'].toString(), - provider: map['provider'].toString(), - providerUid: map['providerUid'].toString(), - providerAccessToken: map['providerAccessToken'].toString(), - providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), - providerRefreshToken: map['providerRefreshToken'].toString(), - ip: map['ip'].toString(), - osCode: map['osCode'].toString(), - osName: map['osName'].toString(), - osVersion: map['osVersion'].toString(), - clientType: map['clientType'].toString(), - clientCode: map['clientCode'].toString(), - clientName: map['clientName'].toString(), - clientVersion: map['clientVersion'].toString(), - clientEngine: map['clientEngine'].toString(), - clientEngineVersion: map['clientEngineVersion'].toString(), - deviceName: map['deviceName'].toString(), - deviceBrand: map['deviceBrand'].toString(), - deviceModel: map['deviceModel'].toString(), - countryCode: map['countryCode'].toString(), - countryName: map['countryName'].toString(), - current: map['current'], - factors: map['factors'] ?? [], - secret: map['secret'].toString(), - mfaUpdatedAt: map['mfaUpdatedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "userId": userId, - "expire": expire, - "provider": provider, - "providerUid": providerUid, - "providerAccessToken": providerAccessToken, - "providerAccessTokenExpiry": providerAccessTokenExpiry, - "providerRefreshToken": providerRefreshToken, - "ip": ip, - "osCode": osCode, - "osName": osName, - "osVersion": osVersion, - "clientType": clientType, - "clientCode": clientCode, - "clientName": clientName, - "clientVersion": clientVersion, - "clientEngine": clientEngine, - "clientEngineVersion": clientEngineVersion, - "deviceName": deviceName, - "deviceBrand": deviceBrand, - "deviceModel": deviceModel, - "countryCode": countryCode, - "countryName": countryName, - "current": current, - "factors": factors, - "secret": secret, - "mfaUpdatedAt": mfaUpdatedAt, - }; - } + /// Session ID. + final String $id; + + /// Session creation date in ISO 8601 format. + final String $createdAt; + + /// Session update date in ISO 8601 format. + final String $updatedAt; + + /// User ID. + final String userId; + + /// Session expiration date in ISO 8601 format. + final String expire; + + /// Session Provider. + final String provider; + + /// Session Provider User ID. + final String providerUid; + + /// Session Provider Access Token. + final String providerAccessToken; + + /// The date of when the access token expires in ISO 8601 format. + final String providerAccessTokenExpiry; + + /// Session Provider Refresh Token. + final String providerRefreshToken; + + /// IP in use when the session was created. + final String ip; + + /// Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). + final String osCode; + + /// Operating system name. + final String osName; + + /// Operating system version. + final String osVersion; + + /// Client type. + final String clientType; + + /// Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). + final String clientCode; + + /// Client name. + final String clientName; + + /// Client version. + final String clientVersion; + + /// Client engine name. + final String clientEngine; + + /// Client engine name. + final String clientEngineVersion; + + /// Device name. + final String deviceName; + + /// Device brand name. + final String deviceBrand; + + /// Device model name. + final String deviceModel; + + /// Country two-character ISO 3166-1 alpha code. + final String countryCode; + + /// Country name. + final String countryName; + + /// Returns true if this the current user session. + final bool current; + + /// Returns a list of active session factors. + final List factors; + + /// Secret used to authenticate the user. Only included if the request was made with an API key + final String secret; + + /// Most recent date in ISO 8601 format when the session successfully passed MFA challenge. + final String mfaUpdatedAt; + + Session({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.userId, + required this.expire, + required this.provider, + required this.providerUid, + required this.providerAccessToken, + required this.providerAccessTokenExpiry, + required this.providerRefreshToken, + required this.ip, + required this.osCode, + required this.osName, + required this.osVersion, + required this.clientType, + required this.clientCode, + required this.clientName, + required this.clientVersion, + required this.clientEngine, + required this.clientEngineVersion, + required this.deviceName, + required this.deviceBrand, + required this.deviceModel, + required this.countryCode, + required this.countryName, + required this.current, + required this.factors, + required this.secret, + required this.mfaUpdatedAt, + }); + + factory Session.fromMap(Map map) { + return Session( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + userId: map['userId'].toString(), + expire: map['expire'].toString(), + provider: map['provider'].toString(), + providerUid: map['providerUid'].toString(), + providerAccessToken: map['providerAccessToken'].toString(), + providerAccessTokenExpiry: map['providerAccessTokenExpiry'].toString(), + providerRefreshToken: map['providerRefreshToken'].toString(), + ip: map['ip'].toString(), + osCode: map['osCode'].toString(), + osName: map['osName'].toString(), + osVersion: map['osVersion'].toString(), + clientType: map['clientType'].toString(), + clientCode: map['clientCode'].toString(), + clientName: map['clientName'].toString(), + clientVersion: map['clientVersion'].toString(), + clientEngine: map['clientEngine'].toString(), + clientEngineVersion: map['clientEngineVersion'].toString(), + deviceName: map['deviceName'].toString(), + deviceBrand: map['deviceBrand'].toString(), + deviceModel: map['deviceModel'].toString(), + countryCode: map['countryCode'].toString(), + countryName: map['countryName'].toString(), + current: map['current'], + factors: map['factors'] ?? [], + secret: map['secret'].toString(), + mfaUpdatedAt: map['mfaUpdatedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "userId": userId, + "expire": expire, + "provider": provider, + "providerUid": providerUid, + "providerAccessToken": providerAccessToken, + "providerAccessTokenExpiry": providerAccessTokenExpiry, + "providerRefreshToken": providerRefreshToken, + "ip": ip, + "osCode": osCode, + "osName": osName, + "osVersion": osVersion, + "clientType": clientType, + "clientCode": clientCode, + "clientName": clientName, + "clientVersion": clientVersion, + "clientEngine": clientEngine, + "clientEngineVersion": clientEngineVersion, + "deviceName": deviceName, + "deviceBrand": deviceBrand, + "deviceModel": deviceModel, + "countryCode": countryCode, + "countryName": countryName, + "current": current, + "factors": factors, + "secret": secret, + "mfaUpdatedAt": mfaUpdatedAt, + }; + } } diff --git a/lib/src/models/session_list.dart b/lib/src/models/session_list.dart index ee4841a2..e4739c9b 100644 --- a/lib/src/models/session_list.dart +++ b/lib/src/models/session_list.dart @@ -2,27 +2,29 @@ part of '../../models.dart'; /// Sessions List class SessionList implements Model { - /// Total number of sessions documents that matched your query. - final int total; - /// List of sessions. - final List sessions; + /// Total number of sessions documents that matched your query. + final int total; - SessionList({ - required this.total, - required this.sessions, - }); + /// List of sessions. + final List sessions; - factory SessionList.fromMap(Map map) { - return SessionList( - total: map['total'], - sessions: List.from(map['sessions'].map((p) => Session.fromMap(p))), - ); - } + SessionList({ + required this.total, + required this.sessions, + }); - Map toMap() { - return { - "total": total, - "sessions": sessions.map((p) => p.toMap()).toList(), - }; - } + factory SessionList.fromMap(Map map) { + return SessionList( + total: map['total'], + sessions: + List.from(map['sessions'].map((p) => Session.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "sessions": sessions.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/subscriber.dart b/lib/src/models/subscriber.dart index 97bdb018..0c926297 100644 --- a/lib/src/models/subscriber.dart +++ b/lib/src/models/subscriber.dart @@ -2,62 +2,70 @@ part of '../../models.dart'; /// Subscriber class Subscriber implements Model { - /// Subscriber ID. - final String $id; - /// Subscriber creation time in ISO 8601 format. - final String $createdAt; - /// Subscriber update date in ISO 8601 format. - final String $updatedAt; - /// Target ID. - final String targetId; - /// Target. - final Target target; - /// Topic ID. - final String userId; - /// User Name. - final String userName; - /// Topic ID. - final String topicId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - - Subscriber({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.targetId, - required this.target, - required this.userId, - required this.userName, - required this.topicId, - required this.providerType, - }); - - factory Subscriber.fromMap(Map map) { - return Subscriber( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - targetId: map['targetId'].toString(), - target: Target.fromMap(map['target']), - userId: map['userId'].toString(), - userName: map['userName'].toString(), - topicId: map['topicId'].toString(), - providerType: map['providerType'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "targetId": targetId, - "target": target.toMap(), - "userId": userId, - "userName": userName, - "topicId": topicId, - "providerType": providerType, - }; - } + /// Subscriber ID. + final String $id; + + /// Subscriber creation time in ISO 8601 format. + final String $createdAt; + + /// Subscriber update date in ISO 8601 format. + final String $updatedAt; + + /// Target ID. + final String targetId; + + /// Target. + final Target target; + + /// Topic ID. + final String userId; + + /// User Name. + final String userName; + + /// Topic ID. + final String topicId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + Subscriber({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.targetId, + required this.target, + required this.userId, + required this.userName, + required this.topicId, + required this.providerType, + }); + + factory Subscriber.fromMap(Map map) { + return Subscriber( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + targetId: map['targetId'].toString(), + target: Target.fromMap(map['target']), + userId: map['userId'].toString(), + userName: map['userName'].toString(), + topicId: map['topicId'].toString(), + providerType: map['providerType'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "targetId": targetId, + "target": target.toMap(), + "userId": userId, + "userName": userName, + "topicId": topicId, + "providerType": providerType, + }; + } } diff --git a/lib/src/models/target.dart b/lib/src/models/target.dart index 50134304..68460126 100644 --- a/lib/src/models/target.dart +++ b/lib/src/models/target.dart @@ -2,57 +2,64 @@ part of '../../models.dart'; /// Target class Target implements Model { - /// Target ID. - final String $id; - /// Target creation time in ISO 8601 format. - final String $createdAt; - /// Target update date in ISO 8601 format. - final String $updatedAt; - /// Target Name. - final String name; - /// User ID. - final String userId; - /// Provider ID. - final String? providerId; - /// The target provider type. Can be one of the following: `email`, `sms` or `push`. - final String providerType; - /// The target identifier. - final String identifier; - - Target({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.userId, - this.providerId, - required this.providerType, - required this.identifier, - }); - - factory Target.fromMap(Map map) { - return Target( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - userId: map['userId'].toString(), - providerId: map['providerId']?.toString(), - providerType: map['providerType'].toString(), - identifier: map['identifier'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "userId": userId, - "providerId": providerId, - "providerType": providerType, - "identifier": identifier, - }; - } + /// Target ID. + final String $id; + + /// Target creation time in ISO 8601 format. + final String $createdAt; + + /// Target update date in ISO 8601 format. + final String $updatedAt; + + /// Target Name. + final String name; + + /// User ID. + final String userId; + + /// Provider ID. + final String? providerId; + + /// The target provider type. Can be one of the following: `email`, `sms` or `push`. + final String providerType; + + /// The target identifier. + final String identifier; + + Target({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.userId, + this.providerId, + required this.providerType, + required this.identifier, + }); + + factory Target.fromMap(Map map) { + return Target( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + userId: map['userId'].toString(), + providerId: map['providerId']?.toString(), + providerType: map['providerType'].toString(), + identifier: map['identifier'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "userId": userId, + "providerId": providerId, + "providerType": providerType, + "identifier": identifier, + }; + } } diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index a55d13c9..43df33a8 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Team class Team implements Model { - /// Team ID. - final String $id; - /// Team creation date in ISO 8601 format. - final String $createdAt; - /// Team update date in ISO 8601 format. - final String $updatedAt; - /// Team name. - final String name; - /// Total number of team members. - final int total; - /// Team preferences as a key-value object - final Preferences prefs; - - Team({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - required this.total, - required this.prefs, - }); - - factory Team.fromMap(Map map) { - return Team( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - total: map['total'], - prefs: Preferences.fromMap(map['prefs']), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "total": total, - "prefs": prefs.toMap(), - }; - } + /// Team ID. + final String $id; + + /// Team creation date in ISO 8601 format. + final String $createdAt; + + /// Team update date in ISO 8601 format. + final String $updatedAt; + + /// Team name. + final String name; + + /// Total number of team members. + final int total; + + /// Team preferences as a key-value object + final Preferences prefs; + + Team({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + required this.total, + required this.prefs, + }); + + factory Team.fromMap(Map map) { + return Team( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + total: map['total'], + prefs: Preferences.fromMap(map['prefs']), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "total": total, + "prefs": prefs.toMap(), + }; + } } diff --git a/lib/src/models/team_list.dart b/lib/src/models/team_list.dart index 23147a1a..817e944f 100644 --- a/lib/src/models/team_list.dart +++ b/lib/src/models/team_list.dart @@ -2,27 +2,28 @@ part of '../../models.dart'; /// Teams List class TeamList implements Model { - /// Total number of teams documents that matched your query. - final int total; - /// List of teams. - final List teams; + /// Total number of teams documents that matched your query. + final int total; - TeamList({ - required this.total, - required this.teams, - }); + /// List of teams. + final List teams; - factory TeamList.fromMap(Map map) { - return TeamList( - total: map['total'], - teams: List.from(map['teams'].map((p) => Team.fromMap(p))), - ); - } + TeamList({ + required this.total, + required this.teams, + }); - Map toMap() { - return { - "total": total, - "teams": teams.map((p) => p.toMap()).toList(), - }; - } + factory TeamList.fromMap(Map map) { + return TeamList( + total: map['total'], + teams: List.from(map['teams'].map((p) => Team.fromMap(p))), + ); + } + + Map toMap() { + return { + "total": total, + "teams": teams.map((p) => p.toMap()).toList(), + }; + } } diff --git a/lib/src/models/token.dart b/lib/src/models/token.dart index 217006c0..35115467 100644 --- a/lib/src/models/token.dart +++ b/lib/src/models/token.dart @@ -2,47 +2,52 @@ part of '../../models.dart'; /// Token class Token implements Model { - /// Token ID. - final String $id; - /// Token creation date in ISO 8601 format. - final String $createdAt; - /// User ID. - final String userId; - /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. - final String secret; - /// Token expiration date in ISO 8601 format. - final String expire; - /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. - final String phrase; - - Token({ - required this.$id, - required this.$createdAt, - required this.userId, - required this.secret, - required this.expire, - required this.phrase, - }); - - factory Token.fromMap(Map map) { - return Token( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - userId: map['userId'].toString(), - secret: map['secret'].toString(), - expire: map['expire'].toString(), - phrase: map['phrase'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "userId": userId, - "secret": secret, - "expire": expire, - "phrase": phrase, - }; - } + /// Token ID. + final String $id; + + /// Token creation date in ISO 8601 format. + final String $createdAt; + + /// User ID. + final String userId; + + /// Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. + final String secret; + + /// Token expiration date in ISO 8601 format. + final String expire; + + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + final String phrase; + + Token({ + required this.$id, + required this.$createdAt, + required this.userId, + required this.secret, + required this.expire, + required this.phrase, + }); + + factory Token.fromMap(Map map) { + return Token( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + userId: map['userId'].toString(), + secret: map['secret'].toString(), + expire: map['expire'].toString(), + phrase: map['phrase'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "userId": userId, + "secret": secret, + "expire": expire, + "phrase": phrase, + }; + } } diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart index 5937ff55..889005cf 100644 --- a/lib/src/models/user.dart +++ b/lib/src/models/user.dart @@ -2,112 +2,130 @@ part of '../../models.dart'; /// User class User implements Model { - /// User ID. - final String $id; - /// User creation date in ISO 8601 format. - final String $createdAt; - /// User update date in ISO 8601 format. - final String $updatedAt; - /// User name. - final String name; - /// Hashed user password. - final String? password; - /// Password hashing algorithm. - final String? hash; - /// Password hashing algorithm configuration. - final Map? hashOptions; - /// User registration date in ISO 8601 format. - final String registration; - /// User status. Pass `true` for enabled and `false` for disabled. - final bool status; - /// Labels for the user. - final List labels; - /// Password update time in ISO 8601 format. - final String passwordUpdate; - /// User email address. - final String email; - /// User phone number in E.164 format. - final String phone; - /// Email verification status. - final bool emailVerification; - /// Phone verification status. - final bool phoneVerification; - /// Multi factor authentication status. - final bool mfa; - /// User preferences as a key-value object - final Preferences prefs; - /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. - final List targets; - /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. - final String accessedAt; - - User({ - required this.$id, - required this.$createdAt, - required this.$updatedAt, - required this.name, - this.password, - this.hash, - this.hashOptions, - required this.registration, - required this.status, - required this.labels, - required this.passwordUpdate, - required this.email, - required this.phone, - required this.emailVerification, - required this.phoneVerification, - required this.mfa, - required this.prefs, - required this.targets, - required this.accessedAt, - }); - - factory User.fromMap(Map map) { - return User( - $id: map['\$id'].toString(), - $createdAt: map['\$createdAt'].toString(), - $updatedAt: map['\$updatedAt'].toString(), - name: map['name'].toString(), - password: map['password']?.toString(), - hash: map['hash']?.toString(), - hashOptions: map['hashOptions'], - registration: map['registration'].toString(), - status: map['status'], - labels: map['labels'] ?? [], - passwordUpdate: map['passwordUpdate'].toString(), - email: map['email'].toString(), - phone: map['phone'].toString(), - emailVerification: map['emailVerification'], - phoneVerification: map['phoneVerification'], - mfa: map['mfa'], - prefs: Preferences.fromMap(map['prefs']), - targets: List.from(map['targets'].map((p) => Target.fromMap(p))), - accessedAt: map['accessedAt'].toString(), - ); - } - - Map toMap() { - return { - "\$id": $id, - "\$createdAt": $createdAt, - "\$updatedAt": $updatedAt, - "name": name, - "password": password, - "hash": hash, - "hashOptions": hashOptions, - "registration": registration, - "status": status, - "labels": labels, - "passwordUpdate": passwordUpdate, - "email": email, - "phone": phone, - "emailVerification": emailVerification, - "phoneVerification": phoneVerification, - "mfa": mfa, - "prefs": prefs.toMap(), - "targets": targets.map((p) => p.toMap()).toList(), - "accessedAt": accessedAt, - }; - } + /// User ID. + final String $id; + + /// User creation date in ISO 8601 format. + final String $createdAt; + + /// User update date in ISO 8601 format. + final String $updatedAt; + + /// User name. + final String name; + + /// Hashed user password. + final String? password; + + /// Password hashing algorithm. + final String? hash; + + /// Password hashing algorithm configuration. + final Map? hashOptions; + + /// User registration date in ISO 8601 format. + final String registration; + + /// User status. Pass `true` for enabled and `false` for disabled. + final bool status; + + /// Labels for the user. + final List labels; + + /// Password update time in ISO 8601 format. + final String passwordUpdate; + + /// User email address. + final String email; + + /// User phone number in E.164 format. + final String phone; + + /// Email verification status. + final bool emailVerification; + + /// Phone verification status. + final bool phoneVerification; + + /// Multi factor authentication status. + final bool mfa; + + /// User preferences as a key-value object + final Preferences prefs; + + /// A user-owned message receiver. A single user may have multiple e.g. emails, phones, and a browser. Each target is registered with a single provider. + final List targets; + + /// Most recent access date in ISO 8601 format. This attribute is only updated again after 24 hours. + final String accessedAt; + + User({ + required this.$id, + required this.$createdAt, + required this.$updatedAt, + required this.name, + this.password, + this.hash, + this.hashOptions, + required this.registration, + required this.status, + required this.labels, + required this.passwordUpdate, + required this.email, + required this.phone, + required this.emailVerification, + required this.phoneVerification, + required this.mfa, + required this.prefs, + required this.targets, + required this.accessedAt, + }); + + factory User.fromMap(Map map) { + return User( + $id: map['\$id'].toString(), + $createdAt: map['\$createdAt'].toString(), + $updatedAt: map['\$updatedAt'].toString(), + name: map['name'].toString(), + password: map['password']?.toString(), + hash: map['hash']?.toString(), + hashOptions: map['hashOptions'], + registration: map['registration'].toString(), + status: map['status'], + labels: map['labels'] ?? [], + passwordUpdate: map['passwordUpdate'].toString(), + email: map['email'].toString(), + phone: map['phone'].toString(), + emailVerification: map['emailVerification'], + phoneVerification: map['phoneVerification'], + mfa: map['mfa'], + prefs: Preferences.fromMap(map['prefs']), + targets: List.from(map['targets'].map((p) => Target.fromMap(p))), + accessedAt: map['accessedAt'].toString(), + ); + } + + Map toMap() { + return { + "\$id": $id, + "\$createdAt": $createdAt, + "\$updatedAt": $updatedAt, + "name": name, + "password": password, + "hash": hash, + "hashOptions": hashOptions, + "registration": registration, + "status": status, + "labels": labels, + "passwordUpdate": passwordUpdate, + "email": email, + "phone": phone, + "emailVerification": emailVerification, + "phoneVerification": phoneVerification, + "mfa": mfa, + "prefs": prefs.toMap(), + "targets": targets.map((p) => p.toMap()).toList(), + "accessedAt": accessedAt, + }; + } } diff --git a/lib/src/realtime.dart b/lib/src/realtime.dart index e02d89a5..35f68677 100644 --- a/lib/src/realtime.dart +++ b/lib/src/realtime.dart @@ -10,9 +10,9 @@ abstract class Realtime extends Service { /// Initializes a [Realtime] service factory Realtime(Client client) => createRealtime(client); - /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used + /// Subscribes to Appwrite events and returns a `RealtimeSubscription` object, which can be used /// to listen to events on the channels in realtime and to close the subscription to stop listening. - /// + /// /// Possible channels are: /// - account /// - collections @@ -41,7 +41,7 @@ abstract class Realtime extends Service { /// /// subscription.close(); /// ``` - /// + /// RealtimeSubscription subscribe(List channels); /// The [close code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5) set when the WebSocket connection is closed. diff --git a/lib/src/realtime_io.dart b/lib/src/realtime_io.dart index 86bf4045..60dc68c7 100644 --- a/lib/src/realtime_io.dart +++ b/lib/src/realtime_io.dart @@ -15,7 +15,6 @@ import 'client_io.dart'; RealtimeBase createRealtime(Client client) => RealtimeIO(client); class RealtimeIO extends RealtimeBase with RealtimeMixin { - RealtimeIO(Client client) { this.client = client; getWebSocket = _getWebSocket; @@ -23,7 +22,8 @@ class RealtimeIO extends RealtimeBase with RealtimeMixin { Future _getWebSocket(Uri uri) async { Map? headers; - while (!(client as ClientIO).initialized && (client as ClientIO).initProgress) { + while (!(client as ClientIO).initialized && + (client as ClientIO).initProgress) { await Future.delayed(Duration(milliseconds: 10)); } if (!(client as ClientIO).initialized) { diff --git a/lib/src/realtime_message.dart b/lib/src/realtime_message.dart index e12b8a4d..372bd0b6 100644 --- a/lib/src/realtime_message.dart +++ b/lib/src/realtime_message.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// Realtime Message class RealtimeMessage { /// All permutations of the system event that triggered this message - /// + /// /// The first event in the list is the most specfic event without wildcards. final List events; diff --git a/lib/src/realtime_mixin.dart b/lib/src/realtime_mixin.dart index fe103280..be87c1bf 100644 --- a/lib/src/realtime_mixin.dart +++ b/lib/src/realtime_mixin.dart @@ -37,7 +37,7 @@ mixin RealtimeMixin { } _createSocket() async { - if(_creatingSocket || _channels.isEmpty) return; + if (_creatingSocket || _channels.isEmpty) return; _creatingSocket = true; final uri = _prepareUri(); try { diff --git a/lib/src/realtime_response.dart b/lib/src/realtime_response.dart index f09da8da..a08eda8e 100644 --- a/lib/src/realtime_response.dart +++ b/lib/src/realtime_response.dart @@ -8,7 +8,6 @@ class RealtimeResponse { required this.type, required this.data, }); - RealtimeResponse copyWith({ String? type, @@ -36,7 +35,8 @@ class RealtimeResponse { String toJson() => json.encode(toMap()); - factory RealtimeResponse.fromJson(String source) => RealtimeResponse.fromMap(json.decode(source)); + factory RealtimeResponse.fromJson(String source) => + RealtimeResponse.fromMap(json.decode(source)); @override String toString() => 'RealtimeResponse(type: $type, data: $data)'; @@ -44,10 +44,10 @@ class RealtimeResponse { @override bool operator ==(Object other) { if (identical(this, other)) return true; - + return other is RealtimeResponse && - other.type == type && - mapEquals(other.data, data); + other.type == type && + mapEquals(other.data, data); } @override